cbind将列表中的多个data.frames中的向量同等命名为单个data.frame

时间:2016-12-16 19:59:30

标签: r list dataframe

我有一个与此类似的列表:

set.seed(1602)
l <- list(data.frame(subst_name = sample(LETTERS[1:10]), perc = runif(10), crop = rep("type1", 10)),
      data.frame(subst_name = sample(LETTERS[1:7]), perc = runif(7), crop = rep("type2", 7)),
      data.frame(subst_name = sample(LETTERS[1:4]), perc = runif(4), crop = rep("type3", 4)),
      NULL,
      data.frame(subst_name = sample(LETTERS[1:9]), perc = runif(9), crop = rep("type5", 9)))

问题:如何提取每个data.frame的subst_name-column并将它们与cbind()(或类似函数)组合到一个新的data.frame而不会弄乱每个data.frame的顺序柱?此外,列应以相应的裁剪类型命名(这可能是因为裁剪类型对于每个data.frame都是唯一的)

编辑:输出应如下所示:

enter image description here

读完评论之后我知道在R中它没有多大意义但是为了在输出中使用data.frame的View选项非常方便。

2 个答案:

答案 0 :(得分:0)

使用给定的示例执行此操作并不正确,因为列表的每个数据帧中的行数不同。但如果你不在乎你可以做:

nullElements = unlist(sapply(l,is.null))
l = l[!nullElements] #delete useless null elements in list
columns=lapply(l,function(x) return(as.character(x$subst_name)))
newDf = as.data.frame(Reduce(cbind,columns))

如果您不想在列中使用回收元素

for(i in 1:ncol(newDf)){
  colLength = nrow(l[[i]])
  newDf[(colLength+1):nrow(newDf),i] = NA
}
newDf = newDf[1:max(unlist(sapply(l,nrow))),] #remove possible extra NA rows

请注意,我编辑了以前的代码,以便从l中删除NULL条目以简化操作

答案 1 :(得分:0)

this SO-Question的帮助下,我提出了以下解决方案。 (可能还有改进的空间)

a <- lapply(l, '[[', 1) # extract the first element of the dfs in the list
a <- Filter(function(x) !is.null(unlist(x)), a) # remove NULLs
a <- lapply(a, as.character)
max.length <- max(sapply(a, length))
## Add NA values to list elements
b <- lapply(a, function(v) { c(v, rep(NA, max.length-length(v)))})
e <- as.data.frame(do.call(cbind, d))
names(e) <- unlist(lapply(lapply(lapply(l, '[[', "crop"), '[[', 2), as.character))