我想对 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 <- 之后),我会收到此错误:
错误在 sample.int(长度 (x), 大小, 替换, 概率) :当"替换 = FALSE"时,无法获取大于总体的样本如果我输入替换 = TRUE,整个表达式都有效。但是,这是不正确的,因为在同一示例中可以绘制一行两次,这是我不希望的。
有没有办法在绘制行时放置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")