2015-04-29 37 views
0

我有一个数据帧列表,我想用所有数据帧的数据创建一个新的数据帧对象。在R中追加数据帧的数据

我不需要检查任何重复性,因为我没有重复的数据,但我找不到一个函数将数据从数据框附加到另一个。

我tryed使用合并功能如下,没有sucess:

折叠是一个列表(),其中每个元素是一个数据帧,都具有相同的结构,但不同的数据。

#Copies the structure to a new Object 
    trainingSub <- folds[[1]][0,] 
    #append data 
    for(y in 1:K){ 
    if(y!=i){ 
     trainingSub <- merge(trainingSub,folds[[y]],all=TRUE) 
    } 
    } 
+0

你有没有在data.table包看了一下'rbindlist'? – dayne

回答

4

通过它的声音,你正在寻找的经典:

do.call(rbind, folds) 

将追加的data.frame名单由部列S在一起。

如果需要通过柱,而不是合并,该方法是:

do.call(cbind, folds) 
2

这个怎么样?

do.call(rbind,folds) 
2

你可以尝试使用rbindlist

library(data.table) 
xmpl <- list(data.frame(a = 1:3), 
      data.frame(a = 4:6), 
      data.frame(a = 7:9)) 

rbindlist(xmpl) 
# a 
# 1: 1 
# 2: 2 
# 3: 3 
# 4: 4 
# 5: 5 
# 6: 6 
# 7: 7 
# 8: 8 
# 9: 9 

rbindlist比较快,但比do.call方法灵活。没有rbindlist相当于快速执行cbind

+2

注意:该函数需要'data.table'包。 – Frank

+0

dayne,你的意思是不那么灵活? – Arun

+1

dayne,那么'do.call' ..不是? – Arun

2

dplyrplyr替代此处列出的其他伟大的方法:

# Using dplyr 
library(dplyr) 
data.frame(rbind_all(folds)) 

# Using plyr 
library(plyr) 
data.frame(rbind.fill(folds)) 

这些都执行相同的功能do.call()rbind但提供一些性能改进。

基准:

folds <- NULL 
for (i in 1:2000) { 
    folds[[i]] <- data.frame(matrix(runif(100), 10, 10)) 
} 

system.time({ x1 <- do.call(rbind, folds) }) 
# user system elapsed 
# 1.11 0.00 1.10 

system.time({ x2 <- data.frame(dplyr::rbind_all(folds)) }) 
# user system elapsed 
# 0.05 0.00 0.05 

system.time({ x3 <- data.frame(plyr::rbind.fill(folds)) }) 
# user system elapsed 
# 0.53 0.00 0.54 

system.time({ x4 <- data.frame(data.table::rbindlist(folds)) }) 
# user system elapsed 
# 0.02 0.00 0.02 

证明,他们都产生同样的结果:

identical(x1, x2) 
# TRUE 
identical(x1, x3) 
# TRUE 
identical(x1, x4) 
# TRUE