我想对大型数据帧执行一些计算。为此,我需要
我该怎么做?
非常感谢您的帮助!
dataframe <- MyDataFrame
nb_obs <- nrow(dataframe) # in my dataframe I have 153 036 rows
nb_chunk <- ceiling(dataframe / 250) # I thus need 613 chunks if I want 250 obs per sub-dataframe
for(i in 1:nb_chunk) {
# my computation here, I want to add a new columns to the chunk to store my results..
}
# then I want to recombine the final dataset (equals to original dataset with a new column added)
编辑部分
感谢您的评论,请使用虹膜数据集在可重现的示例中找到我的建议。
此阶段我还有两个问题:
有没有更好的方法来继续使用dplyr?
df <- iris # using iris as an example (my real dataframe is 153036 rows and 17 columns)
nb_obs <- nrow(df) # nb of observations in the dataframe (thus nb of operations to be performed)
nb_obs_in_chunk <- 13 # nb of rows per chunk
nb_chunk <- ceiling(nb_obs / nb_obs_in_chunk) # total nb of chunks to be created
nb_chunk_full <- floor(nb_obs / nb_obs_in_chunk) # nb of chunks to be created with nb_obs_in_chunk rows
nb_obs_last_chunk <- nb_obs - nb_obs_in_chunk*nb_chunk_full # nb of rows in final chunks
df$split.factor <- as.factor(c(rep(1:nb_chunk_full, each = nb_obs_in_chunk), rep(nb_chunk_full + 1, nb_obs_last_chunk))) # create factor to split dataframe into equal parts
final.df <- data.frame(Sepal.Length = numeric(), Sepal.Width = numeric(), Petal.Length = numeric(), Petal.Width = numeric(), Species = factor(), split.factor = factor()) # initiate final dataframe (desired output)
for(i in 1:nb_chunk) {
temp_i <- df[df$split.factor == i, ]
temp_i$NEW <- temp_i$Sepal.Length + temp_i$Sepal.Width
final.df <- rbind(final.df, temp_i)
}
答案 0 :(得分:4)
回答您的初步问题:
df <- iris
do.call(rbind,
lapply(split(df, rep(seq(13), length.out = 150, each = 13)),
function(chunk) {
chunk$NEW = chunk$Sepal.Length + chunk$Sepal.Width
chunk
})
)
rep(seq(13), length.out = 150, each = 13)
与您示例中的split.factor
列相同,split()
函数将其转换为因子。
这也回答了编辑中的第一个问题:是的,您不需要初始化最终数据框。
请注意,行名称不再是从1到150的序列,因为它们现在包含块号。
答案 1 :(得分:1)
我认为这样做:
library("dplyr")
ddf <- iris
nb_obs_in_chunk <- 13
ddf %>% mutate(id=seq(nrow(ddf)),
chunk=cut(id,id %/% nb_obs_in_chunk)) %>%
group_by(chunk) %>%
mutate(NEW=Sepal.Length+Sepal.Width)
但尚未经过测试...... @ mjkallen rep(seq(13), length.out = 150, each = 13))
可能比我基于%/%
的解决方案更能获得大块数字。