根据数据帧的长度将数据帧拆分为相等的部分

时间:2014-08-27 20:47:07

标签: r split dataframe

问题:我需要将几个不同的大型数据帧(例如50k行)划分为更小的块,每个块具有相同的行数。但是,我不想手动设置每个数据集的块大小。相反,我想要代码:

  • 检查数据帧的长度并确定有多少块 大约几千行,原始数据帧可以分解为
  • 最大限度地减少"剩余的数量"必须丢弃的行

此处提供的答案相关:Split a vector into chunks in R

但是,我不想手动设置块大小。我希望代码找到"最佳"块大小可以最大限度地减少剩余部分。

示例:(基于Harlan在上面链接中的回答)

df <- rnorm(20752)
max <- 20
x <- seq_along(df)
df <- split(df, ceiling(x/max))
str(df)
> List of 5
> $ 1: num [1:5000] -1.4 -0.496 -1.185 -2.071 -1.118 ...
> $ 2: num [1:5000] 0.522 1.607 -2.228 -2.044 0.997 ...
> $ 3: num [1:5000] 0.295 0.486 -1.085 0.515 0.96 ...
> $ 4: num [1:5000] 0.695 -0.58 -1.676 1.052 1.266 ...
> $ 5: num [1:752] -0.6468 0.1731 0.5788 -0.0584 0.8479 ...

如果我选择了4100行的块大小,我将有5个块,其余252行。这更令人满意,因为我会丢弃更少的数据点。只要块至少有几千行,我就不在乎它们的大小。

1 个答案:

答案 0 :(得分:3)

这是一种蛮力方法(但非常快):

# number of rows of your data.frame (from your example... )
nrows <- 20752

# acceptable range for sub-data.frame size
subSetSizes <- 4000:10000

remainders <- nrows %% subSetSizes 
minIndexes <- which(remainders == min(remainders))
chunckSizesHavingMinRemainder <- subSetSizes[minIndexes]

# > chunckSizesHavingMinRemainder
# [1] 5188

# the remainder of 20752 / 5188 is indeed 0 (the only minimum)
# nrows %% 5188 
# > [1] 0
相关问题