【发布时间】:2013-06-23 22:27:22
【问题描述】:
我有一个dataframe,其中所有行都有一个值uid,对应于一个用户ID,并且多行可以有相同的uid。我想为每个 uid 创建一个仅包含 x 行的随机样本的新数据框。
我写了这个函数:
trim <- function(df, max){
data.by.user <- split(df, df$uid) #split the dataframe by user
output <- NULL
lapply(data.by.user, function(x){
#length(x$tid) = number of rows for that user
if(is.null(output){
if(length(x$tid) <= max){
output <<- x
}
}else{
output <<- x[sample(nrow(x), size = max),]
}
}else if (length(x$tid) <= max){
output <<- rbind(output, x)
}else{
output <<- rbind(output, x[sample(nrow(x), size=max),]) #sample 'max' rows from x
}
})
return(output)
}
但是当我在我的数据框(有几百万行)上尝试它时,
d <- trim(old_df, 200)
它耗尽内存并收到此错误以及有关已达到内存总分配的警告:
Error: cannot allocate vector of size 442 Kb
有没有更节省内存的方法来实现这一点?
【问题讨论】: