Search code examples
rmergecbind

cbind error when merging list containing empty data frames


When trying this code., I got an error. 'a' is a list of dataframes consisting of data extracted from files in b. There are some empty dataframes/records in 'a':

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

I got this error:

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

Anyway I can rectify this issue?


Solution

  • If there are empty list elements, we can remove those

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

    Or create the condition within Map itself

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

    assuming that otherwise the corresponding list elements have the same number of rows

    If we need to get the originaldataset in case one of them is empty, we can do

    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)
    

    data

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