且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将数据帧随机分成n个相等的部分

更新时间:2021-09-23 21:36:33

您可以将cutsplit结合使用来进行此操作:

You can use cut with split to do this:

k <- 4
str(
    lapply(df_list, function(df) {
        n <- nrow(df)
        split(df, cut(sample(n), seq(0, (k+1)*ceiling(n/k), by=ceiling(n/k)), labels=FALSE))
    })
)

输出:

List of 8
 $ AB_df:List of 4
  ..$ 1:'data.frame':   51 obs. of  2 variables:
  .. ..$ X1: int [1:51] 13 50 84 6 109 125 88 120 38 41 ...
  .. ..$ X2: int [1:51] 36 107 14 71 92 115 130 126 111 67 ...
  ..$ 2:'data.frame':   50 obs. of  2 variables:
  .. ..$ X1: int [1:50] 42 105 73 72 36 69 110 43 118 121 ...
  .. ..$ X2: int [1:50] 23 81 96 52 97 42 82 102 89 89 ...
  ..$ 3:'data.frame':   50 obs. of  2 variables:
  .. ..$ X1: int [1:50] 67 128 78 105 32 41 19 86 69 120 ...
  .. ..$ X2: int [1:50] 116 85 55 1 110 96 67 101 73 48 ...
  ..$ 4:'data.frame':   50 obs. of  2 variables:
  .. ..$ X1: int [1:50] 20 104 33 83 73 24 23 129 44 69 ...
  .. ..$ X2: int [1:50] 13 100 74 14 0 59 55 80 72 2 ...
 $ BC_df:List of 4
  ..$ 1:'data.frame':   51 obs. of  2 variables:
  .. ..$ X1: int [1:51] 58 85 40 68 30 32 111 96 35 51 ...
  .. ..$ X2: int [1:51] 71 24 12 50 87 61 17 65 11 43 ...
  ..$ 2:'data.frame':   50 obs. of  2 variables:
  .. ..$ X1: int [1:50] 10 54 91 105 65 39 26 78 123 12 ...
  .. ..$ X2: int [1:50] 117 31 6 114 73 11 58 93 106 21 ...
.........................................................

数据:

set.seed(0L)    
AB_df = data.frame(replicate(2,sample(0:130,201,rep=TRUE)))
BC_df = data.frame(replicate(2,sample(0:130,200,rep=TRUE)))
DE_df = data.frame(replicate(2,sample(0:130,197,rep=TRUE)))
FG_df = data.frame(replicate(2,sample(0:130,203,rep=TRUE)))

AB_pc = data.frame(replicate(2,sample(0:130,201,rep=TRUE)))
BC_pc = data.frame(replicate(2,sample(0:130,200,rep=TRUE)))
DE_pc = data.frame(replicate(2,sample(0:130,197,rep=TRUE)))
FG_pc = data.frame(replicate(2,sample(0:130,203,rep=TRUE)))

df_list = list(AB_df, BC_df, DE_df, FG_df, AB_pc, BC_pc, DE_pc, FG_pc)
names(df_list) = c("AB_df", "BC_df", "DE_df", "FG_df", "AB_pc", "BC_pc", "DE_pc", "FG_pc")