[R] Bind element of List of matrix or data.frame or list
2016-01-09 01:59
323 查看
Alternative solutions for list of matrix or dataframe
Alternative solutions for list of list
Firstly, I generate toy data
Now I list the alternative solutions
From the codes, we can see that
for matrix, only
for data.frame, all
And now benchmark for all solutions
Alternative solutions for list of list
1. Alternative solutions for list of matrix or data.frame
If I have a list of matrix or data.frame, we can use the following ways to bind the rows of all elements.Firstly, I generate toy data
myList1 <- list(matrix(rnorm(2*3), ncol=2), matrix(rnorm(2*3), ncol=2), matrix(rnorm(2*3), ncol=2), matrix(rnorm(2*3), ncol=2)) myList2 <- list(as.data.frame(matrix(rnorm(2*3), ncol=2)), as.data.frame(matrix(rnorm(2*3), ncol=2)), as.data.frame(matrix(rnorm(2*3), ncol=2)), as.data.frame(matrix(rnorm(2*3), ncol=2)))
Now I list the alternative solutions
# solution 1 result1.1 <- do.call(rbind, myList1) head(result1.1) result1.2 <- do.call(rbind, myList2) head(result1.2) # solution 2 ## plyr: the split-apply-combine paradigm for R library(plyr) result1.2.1 <- ldply(myList1, rbind) head(result1.2.1) ###Error: All inputs to rbind.fill must be data.frames result1.2.2 <- rbind.fill(myList1) head(result1.2.2) result2.2.1 <- ldply(myList2, rbind) head(result2.2.1) result2.2.2 <- rbind.fill(myList2) head(result2.2.2) # solution 3 ## data.table: Enhanced data.frame library(data.table) ###Error in rbindlist(myList1) : Item 1 of list input is not a data.frame, data.table or list result1.3 <- rbindlist(myList1) head(result1.3) result2.3 <- rbindlist(myList2) head(result2.3)
From the codes, we can see that
for matrix, only
do.call(rbind, ), ldplycan work.
for data.frame, all
do.call(rbind, ), ldply, rbind.fill, rbindlistcan work.
And now benchmark for all solutions
# benchmark ## benchmark: a simple wrapper around system.time library(rbenchmark) benchmark(do.call(rbind, myList2), ldply(myList2, rbind), rbind.fill(myList2), rbindlist(myList2))
2. Alternative solutions for list of list
#############list of list############################# # generate list of list myList3 <- vector("list", 4) for(i in 1:4){ myList3[[i]] <- vector("list", 2) for(j in 1:2){ myList3[[i]][[j]] <- rnorm(3) } } # bind each element of outer list tempList <- lapply(myList3, function(z)do.call(rbind,z)) ## selection operator "[" bind.ith.rows <- function(i) do.call(rbind, lapply(tempList, "[", i, TRUE)) nr <- nrow(tempList[[1]]) lapply(1:nr, bind.ith.rows)
相关文章推荐
- 向大家推荐一个收集整理正则表达式的网站
- 最严谨的校验email地址的正则表达式及各种语言对应版
- JAVA中正则表达式匹配,替换,查找,切割的方法
- iOS中使用正则表达式NSRegularExpression 来验证textfiled输入的内容
- 处理Plot rendering error
- R语言书籍的学习路线图
- 20120919_01
- 20120919_02
- 20120919_3
- Review JDBC
- Win2003SN
- 解决rJava无法找到jvm.dll的问题
- System Center 2012
- How to configure a RPC Client Access
- R改工作空间
- R语言基础画图
- R的若干基因及争论
- KVM或Xen遇到Unable to retrieve http images/install.img
- Linux Mint安装最新版R
- R NOTE -- learn intro