我有一个名字列表。我试图从名称中提取重复的($ 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。我该怎么做才能解决此问题?
答案 0 :(得分:1)
您可能想要使用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是矢量化的,因此最好不要执行此循环,因为它更快,更简洁:
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)))
,但要输入的内容更多。