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

时间:2015-10-05 15:22:39

标签: 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),])

有更优雅的方法吗?我假设这种类型的操作经常在其他代码中完成。

2 个答案:

答案 0 :(得分:6)

如果你想保留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),]))
}

答案 1 :(得分:2)

您可以使用splitchuncksize至少cumsum行的小组来使用modulo

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
相关问题