【发布时间】:2022-01-20 14:22:24
【问题描述】:
我正在寻找一种方法来使用 sample() 根据 data.table 的另一列中的值从不同列表中采样值 - 目前我收到递归索引失败错误 - 代码等解释如下:
先设置示例数据:
library(stats)
library(data.table)
# list of three different nest survival rates
survival<-list(0.91,0.95,0.99)
# incubation period
inc.period<-28
# then set up function to use the geometric distribution to generate 3 lists of incubation outcomes based on the nest survivals and incubation period above.
# e.g. less than 28 is a nest failure, 28 is a successful nest.
create.sample <- function(survival){
outcome<-rgeom(100,1-survival)
fifelse(outcome > inc.period, inc.period, outcome)
}
# then create list of 100 nest outcomes with 3 different survival values using lapply
inc.outcomes <- lapply(survival,create.sample)
# set up a data.table - each row of data will be a nest.
index<-c(1:3)
iteration<-1:20
dt = CJ(index,iteration)
然后我想创建一个新列“inc.period”,它使用 dt 的索引列从“inc.outcomes”列表中采样,以选择三个“inc.outcomes”列表中的哪一个进行采样(使用每行数据使用不同的样本)。 所以例如当 index = 1 时,采样值来自 inc.outcomes[[1]] - 这是低巢生存列表,当 index = 2 时,我从 inc.outcomes[[2]] 等中采样。
代码看起来像这样,但这不起作用(我收到递归索引失败错误):
dt[,inc.period:= sample(inc.outcomes[[index]],nrow(dt),replace = TRUE)]
感谢您收到任何帮助或建议,以及针对此问题的不同方法的建议 - 这是为了更新在闪亮模拟中运行的代码,因此首选更快的选项!
【问题讨论】:
标签: r random data.table