重复样本并将它们添加到数据框

Repeating Samples and Adding them to a Dataframe

我有一份名单。我正在尝试从名称中重复 ($n = 1000$) 个样本,并将它们添加到 R 中的数据框中。

names <- c("A", "B", "3", "4", "5", "6", "7", "8", "9", "10")
df <- data.frame(names)

for(i in 1:1000) {
  output <- sample(names, size = 10, replace = F)
  df <- mutate(df, output)
}

不幸的是,我只得到一个输出列,而不是 1000 个。我该怎么做才能解决这个问题?

您可能想使用 cbind 或类似的,就像这样。还需要 setNames 以避免重复的列名。

set.seed(42)
for(i in 1:5) {
  output <- sample(names, size=length(names), replace=F)
  df <- setNames(cbind.data.frame(df, output), c(names(df), paste0("output", i)))
}
df
#    names output1 output2 output3 output4 output5
# 1      A       A       8       9       3       5
# 2      B       5       7      10       A       4
# 3      3      10       4       3       B       B
# 4      4       8       A       4       6       8
# 5      5       B       5       5      10       3
# 6      6       4      10       6       8       A
# 7      7       6       B       A       4      10
# 8      8       9       6       B       5       7
# 9      9       7       9       8       7       6
# 10    10       3       3       7       9       9

或者,由于 R 是矢量化的,所以最好执行此 w/o 循环,因为它更快、更简洁:

set.seed(42)
R <- 5
cbind(df, `colnames<-`(replicate(R, sample(names)), paste0("output", 1:R)))
#    names output1 output2 output3 output4 output5
# 1      A       A       8       9       3       5
# 2      B       5       7      10       A       4
# 3      3      10       4       3       B       B
# 4      4       8       A       4       6       8
# 5      5       B       5       5      10       3
# 6      6       4      10       6       8       A
# 7      7       6       B       A       4      10
# 8      8       9       6       B       5       7
# 9      9       7       9       8       7       6
# 10    10       3       3       7       9       9

注:我这里用的是`colnames<-`,相当于setNames的矩阵。不过,您也可以输入 cbind(df, setNames(replicate(R, sample(names), simplify=FALSE), paste0("output", 1:R))),但输入更多。