【问题标题】:cbind error when merging list containing empty data frames合并包含空数据框的列表时出现 cbind 错误
【发布时间】:2021-01-24 02:57:24
【问题描述】:

在尝试此代码时,我遇到了错误。 'a' 是一个数据框列表,由从 b 中的文件中提取的数据组成。 'a' 中有一些空的数据框/记录:

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

无论如何我可以纠正这个问题?

【问题讨论】:

  • 你能检查一下sapply(a, dim)sapply(b, dim)
  • 如果一个列表元素为空,是否要保留该列表元素

标签: r merge cbind


【解决方案1】:

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

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))

【讨论】:

  • Map() 内部的另一种可能性(取决于他们想要什么)是if(nrow(x) == 0) {return(y)},反之亦然。
  • 我试过Map,但得到了他的错误Error in if (nrow(x) == 0) { : argument is of length zero
  • @Jane 如果您查看我的示例,它对我有用
  • @@Jane 你能用is.null试试我的Map的更新版本吗
  • @akrun 现在可以工作了,但是当我随后尝试使用 rbind 时,我遇到了这个错误Error in rbindlist(a, fill = TRUE) : Item 2 of input is not a data.frame, data.table or list 如何删除那些空记录,例如第 2 项?
【解决方案2】:

您可以检查a 中的行,如果为空cbind,则两个数据框else 返回原始数据框。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-17
    • 2021-11-18
    • 2019-01-21
    • 2020-02-01
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    • 2018-07-25
    相关资源
    最近更新 更多