我正在寻找一些方法来迭代R中的块,但是现在我必须在末尾添加一个额外的语句来捕获余数,如果项目的数量没有均匀地划分为chunksize.例如:
for (i in 1:(nrow(dataframe)/chunksize)){
(do something with chunk)
}
remainder <- nrow(dataframe) %% chunksize
(do something with dataframe[(length(dataframe)-remainder):length(dataframe),])
Run Code Online (Sandbox Code Playgroud)
有没有更优雅的方式来做到这一点?我假设这种类型的操作在其他代码中经常进行.
如果你想要保留for构造:
chunk_size <- 7
for (i in seq(1, nrow(mtcars), chunk_size)) {
seq_size <- chunk_size
if ((i + seq_size) > nrow(mtcars)) seq_size <- nrow(mtcars) - i + 1
cat(i, seq_size, "\n")
}
1 7
8 7
15 7
22 7
29 4
Run Code Online (Sandbox Code Playgroud)
您可以使用它来处理您需要的索引.
这是一个没有if:
chunk_size <- 7
chunks <- ggplot2::cut_interval(1:nrow(mtcars), length=chunk_size, labels=FALSE)
for (i in unique(chunks)) {
print(nrow(mtcars[which(chunks==i),]))
}
Run Code Online (Sandbox Code Playgroud)
您可以使用split通过利用至少一组chuncksize行与cumsum和modulo:
n = chuncksize
lst = split(df, cumsum((1:nrow(df)-1)%%n==0))
lapply(lst, function(df_)
{
#some code on df_
})
Run Code Online (Sandbox Code Playgroud)
例子:
df = data.frame(col1=letters[1:10])
n = 3 #you want small dataframes of 3 rows
#> split(df, cumsum(1:nrow(df)%%n==0))
#$`1`
# col1
#1 a
#2 b
#3 c
#$`2`
# col1
#4 d
#5 e
#6 f
#$`3`
# col1
#7 g
#8 h
#9 i
#$`4`
# col1
#10 j
Run Code Online (Sandbox Code Playgroud)