如何随机拆分 R 中的数据帧?

Lan*_*nza 5 r dataframe

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

akr*_*run 5

我们sample通过将 1 到 8size作为数据集的行数来创建分组变量,split在 a 中具有分组变量的行的序列list,循环遍历list( 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 
Run Code Online (Sandbox Code Playgroud)

正如@RHertel 在评论中提到的,我们可以做一秒钟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),])
Run Code Online (Sandbox Code Playgroud)

数据

set.seed(24)
df1 <- data.frame(V1= 1:1000, V2= rnorm(1000))
Run Code Online (Sandbox Code Playgroud)