合并包含空数据框的列表时出现 cbind 错误

cbind error when merging list containing empty data frames

尝试此代码时,出现错误。 'a' 是一个数据帧列表,由从 b 中的文件中提取的数据组成。 'a'中有一些空的dataframes/records:

b <- list.files(path=".", pattern=".xlsx")
c <- Map(cbind, b, a) 

我收到这个错误:

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 1, 0

我能解决这个问题吗?

如果有空列表元素,我们可以删除那些

i1 <- (sapply(b, nrow) > 0) & (sapply(a, nrow) > 0)
Map(cbind, b[i1], a[i1])

或在 Map 自身内创建条件

out <- Map(function(x, y) if(nrow(x) > 0 & nrow(y) > 0) cbind(x, y), b, a)

假设相应的 list 元素具有相同的行数

如果我们需要在其中一个为空的情况下获取原始数据集,我们可以这样做

Map(function(x, y) if(is.null(x)|NROW(x) == 0) {
              y} else if(is.null(y)|NROW(y) == 0) {
              x} else cbind(x, y), 
          b, a)

数据

a <- list(head(mtcars), data.frame(col1 = numeric(0)), head(iris))
b <- list(data.frame(col1 = numeric(0)), head(iris), head(mtcars))

您可以检查 a 中的行,如果它是空的 cbind 两个数据帧 else return 原始数据帧。

Map(function(x, y) if (nrow(y)) cbind(x, y) else x, b, a)