【问题标题】:How can I split a data frame in R randomly?如何随机拆分 R 中的数据框?
【发布时间】:2016-04-16 10:45:59
【问题描述】:

我有一个 ca 的数据框。 1000 行,我想将其随机拆分为 8 个较小的数据帧,每个数据帧包含 100 个元素。我尝试在数据框上使用 sample 函数 8 次,但有时它会选择相同的行。

【问题讨论】:

  • 另一种方法可能是split(df, sample(rep(1:10, each=100)))[1:8],但我目前无法测试。
  • 或随机订购,选择800split(df1[order(runif(1000))[1:800], ], 1:8)

标签: r dataframe


【解决方案1】:

我们通过sampleing 1 到 8 创建一个分组变量,size 作为数据集的行数,split 分组变量在list 中的行序列,循环通过@ 987654325@ (lapply(...),对数据集进行子集化,得到前100行head

lst <- lapply(split(1:nrow(df1), sample(1:8, nrow(df1), replace=TRUE, prob = rep(1/8, 8))),
           function(i) head(df1[i,],100))
sapply(lst, nrow)
#  1   2   3   4   5   6   7   8 
#100 100 100 100 100 100 100 100 

正如@RHertel 在 cmets 中提到的,我们可以再做一次sample 来获得 100 行

lst <- lapply(split(1:nrow(df1), sample(1:8, nrow(df1), replace=TRUE, prob = rep(1/8, 8))),
       function(i) df1[sample(i, 100, replace=FALSE),])

数据

set.seed(24)
df1 <- data.frame(V1= 1:1000, V2= rnorm(1000))

【讨论】:

  • 24 是你最喜欢的数字@akrun 吗?
  • @RHertel 感谢 cmets。我认为这是有道理的。包括那个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-28
  • 2020-12-31
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
相关资源
最近更新 更多