我想通过从模拟表(table\simul)生成航班号来模拟航班号,以观察表为基础.

table_simul <- data.table(
  date_f = c("2020-01-01","2020-01-02","2020-01-03","2020-01-03"),
  city = c("Paris","Paris","London", "Berlin")
)

table_obs <- data.table(
  city = c("Paris","Paris","Paris","London","London", "Berlin"),
  flight = c(1,2,7,4,5,14),
  weight = c(0.33,0.33,0.33,0.5,0.5,1)
)

使用的数据:

 Table simul:
    
date        city

2020-01-01  Paris
2020-01-01  Paris
2020-01-01  London
2020-01-01  Berlin


Table obs
---------
city   flight   weight

Paris   1        0.33
Paris   2        0.33
Paris   7        0.33
London  4        0.5
London  5        0.5
Berlin  14       1

预期结果:

date_f        city     flight
2020-01-01  Paris       2
2020-01-02  Paris       2
2020-01-03  London      4
2020-01-03  Berlin      14

我想使用数据表包,因为数据量非常大.

get_flight_sample <- function(param_city){
  table_simul[city==param_city]
  res <- sample(table_obs$flight,1, replace=T, prob = table_obs$weight)
}

res <- table_simul[,.(flight = get_flight_sample(city))]

推荐答案

可以使用助手函数从table_obs中采样,然后与table_simul合并

f <- function(i, ...) {
  if(length(i) == 1) i else sample(i, size = 1, ...)
}

set.seed(42)
tmp <- table_obs[, .(flight = f(flight, prob = weight)), by = city]
table_simul[, flight := tmp[table_simul, on = .(city)]$flight]
table_simul
#       date_f   city flight
#1: 2020-01-01  Paris      1
#2: 2020-01-02  Paris      1
#3: 2020-01-03 London      4
#4: 2020-01-03 Berlin     14

R相关问答推荐

使用spatVector裁剪网格数据时出现的问题

为什么观察不会被无功值变化触发?

我想在R中总结一个巨大的数据框架,使我只需要唯一的lat、lon、Date(Year)和Maxium Value""""""""

当我们有多个特殊字符时,使用gsub删除名称和代码'

对于变量的每个值,仅 Select 包含列表中所有值的值.R

使用较长的查询提取具有部分匹配的列表中的较短目标,

在RStudio中堆叠条形图和折线图

线性模型斜率在减少原始数据时提供NA

如何识别倒排的行并在R中删除它们?

更改STAT_VALLES/STAT_PEAKS中的箭头线宽/大小

从多面条形图中删除可变部分

从多层嵌套列表构建Tibble?

在使用具有Bray-Curtis相似性的pvCluust时计算p值

如何在ggplot2中创建多个y轴(每个变量一个)

使用ggplot2中的sec_axis()调整次轴

减少雨云面之间的间距并绘制所有统计数据点

按组使用dummy r获取高于标准的行的平均值

我正在try 创建一个接近cos(X)的值的While循环,以便它在-或+1-E10范围内

R中的交叉表

在R中,如果一个值在同一数据帧中的任何特定列中,如何计算?