R无需替换即可复制示例功能

R replicate sample function without replacement

我想对 5 个随机行进行 1,000 次采样并将它们汇总到一个数据框中。我对 replace = FALSE 有疑问,我想知道将它放到 replace = TRUE.

的位置

我有一个 5,000 行的数据集,看起来(简化)如下:

 Fund.ID Vintage Type Region.Focus Net.Multiple  Size
[1,] 4716  2003  2    US           1.02          Small
[2,] 2237  1998  25   Europe       0.03          Medium
[3,] 1110  1992  2    Europe       1.84          Medium
[4,] 12122 1997  25   Asia         2.04          Large 
[5,] 5721  2006  25   US           0.86          Mega
[6,] 730   1998  2    Europe       0.97          Small

这是我的函数,它从一个随机行开始,包括对绘制的 5 行的约束。:

       simulate <- function(inv.period) {
          start <- sample_n(dataset, 1, replace=TRUE) #draw random first fund
          t <- start$Vintage:(start$Vintage + inv.period) #define investment period contingent on first fund
          fof <- dataset[sample(which(dataset$Vintage %in% t), 5, replace = FALSE), ] #include constraint, 5 funds in portfolio
        }

#replicate this function 1,000 times 
#and give out as a data frame with portfolios classified
        library(plyr)
        library(dplyr)
        fof.5 <- rdply(1000, simulate(4))
        rename(fof.5, FoF.ID = .n)

如果我在模拟函数中使用 replace=FALSE(在 fof <- 之后),我会得到这个错误:

Error in sample.int(length(x), size, replace, prob) : cannot take a sample larger than the population when 'replace = FALSE' The whole expression works if I put replace = TRUE. However, this would not be correct, as a row could be drawn twice in the same sample, which I do not want.

有没有办法在画行的时候放replace=FALSE,而对整个数据集放replace=TRUE?应该是:一行只能在样本中绘制一次,但可以在另一个样本中再次绘制。

我建议把dplyr的东西去掉,没必要。其次,为匹配项添加一个名为 matches 的变量,然后对该向量的长度或数字 5 进行采样,以较小者为准。最后,我会使用 data.table::rbindlist,它有一个参数来创建一个索引,指示进行了哪个平局。输出将是一个data.table,如果你不熟悉它,你可以在最后使用as.data.frame(rbindlist(....))将它转回一个data.frame.:

library(data.table)
simulate <- function(inv.period) {
  start <- dataset[sample(nrow(dataset), 1, replace=TRUE),]
  t <- start$Vintage:(start$Vintage + inv.period)
  matches <- which(dataset$Vintage %in% t)
  dataset[sample(matches, min(length(matches),5), replace = FALSE), ]
}

r <- replicate(1000, simulate(5), simplify=FALSE)
rbindlist(r, idcol="draw")