【问题标题】:Repeating Samples and Adding them to a Dataframe重复样本并将它们添加到数据框中
【发布时间】:2020-09-23 15:58:45
【问题描述】:

我有一个名字列表。我正在尝试从名称中重复 ($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 个。我能做些什么来解决这个问题?

【问题讨论】:

  • 你的预期输出是什么?
  • 如果你想要 1000 列,你会做as.data.frame(replicate(1000, sample(names)))。如果你想要一个单列,它是c(replicate(1000, sample(names)))

标签: r dataframe for-loop sample


【解决方案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&lt;-`,它是setNames 的矩阵等价物。不过,您也可以输入cbind(df, setNames(replicate(R, sample(names), simplify=FALSE), paste0("output", 1:R))),但要输入更多内容。

【讨论】:

  • 这比它需要的要慢得多。如何使用replicate 或类似方法一次制作整个df 并使用setNames(paste(.. 等重命名?
  • 当然,已经在我的剪贴板 @AllanCameron 中提到了这一点,出于教学原因,我认为最好解决实际问题并提供一个可能更好的替代方案,你知道的。
  • 当然。我知道你的意思 - 这样 OP 就会发现他们做错了什么以及正确的方法。 +1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-09
  • 2016-06-21
  • 2013-04-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多