我想将数据帧分成4个等份,因为我想使用我的计算机的4个核心.
我这样做了:
df2 <- split(df, 1:4)
unsplit(df2, f=1:4)
Run Code Online (Sandbox Code Playgroud)
然后
df2 <- split(df, 1:4)
unsplit(df2, f=c('1','2','3','4')
Run Code Online (Sandbox Code Playgroud)
但是unsplit功能不起作用,我有这些警告信息
1: In split.default(seq_along(x), f, drop = drop, ...) :
data length is not a multiple of split variable
...
Run Code Online (Sandbox Code Playgroud)
你知道原因吗?
中有多少行df
?如果表中的行数不能被4整除,您将收到该警告.我认为您f
错误地使用了拆分因子,除非您要执行的操作是将每个后续行放入不同的拆分data.frame中.
如果您真的想将数据拆分为4个数据帧.一行接着另一行然后使您的分割因子与数据帧中的行数相同,使用rep_len
如下:
## Split like this:
split(df , f = rep_len(1:4, nrow(df) ) )
## Unsplit like this:
unsplit( split(df , f = rep_len(1:4, nrow(df) ) ) , f = rep_len(1:4,nrow(df) ) )
Run Code Online (Sandbox Code Playgroud)
希望这个例子说明错误发生的原因以及如何避免它(即使用适当的分裂因子!).
## Want to split our data.frame into two halves, but rows not divisible by 2
df <- data.frame( x = runif(5) )
df
## Splitting still works but...
## We get a warning because the split factor 'f' was not recycled as a multiple of it's length
split( df , f = 1:2 )
#$`1`
# x
#1 0.6970968
#3 0.5614762
#5 0.5910995
#$`2`
# x
#2 0.6206521
#4 0.1798006
Warning message:
In split.default(x = seq_len(nrow(x)), f = f, drop = drop, ...) :
data length is not a multiple of split variable
## Instead let's use the same split levels (1:2)...
## but make it equal to the length of the rows in the table:
splt <- rep_len( 1:2 , nrow(df) )
splt
#[1] 1 2 1 2 1
## Split works, and f is not recycled because there are
## the same number of values in 'f' as rows in the table
split( df , f = splt )
#$`1`
# x
#1 0.6970968
#3 0.5614762
#5 0.5910995
#$`2`
# x
#2 0.6206521
#4 0.1798006
## And unsplitting then works as expected and reconstructs our original data.frame
unsplit( split( df , f = splt ) , f = splt )
# x
#1 0.6970968
#2 0.6206521
#3 0.5614762
#4 0.1798006
#5 0.5910995
Run Code Online (Sandbox Code Playgroud)