繁体   English   中英

优雅的方式循环块与剩余的r?

[英]elegant way to loop over chunks with remainder in r?

我正在寻找一些方法来迭代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),])

有没有更优雅的方式来做到这一点? 我假设这种类型的操作在其他代码中经常进行。

如果你想要保留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 

您可以使用它来处理您需要的索引。

这是一个没有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),]))
}

您可以通过使用cumsummodulo至少包含chuncksize行的组来使用split

n = chuncksize
lst = split(df, cumsum((1:nrow(df)-1)%%n==0))

lapply(lst, function(df_)
{
    #some code on df_
})

例:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM