Search code examples
rradix

Rbind does not carry the colnames of a empty data.frame over


How to rbind with empty data.frame? It only carries the column names when there is at least one row but not when it is empty. Empty data.frame is often created before the for loop, so this behavior is annoying.

Example:

test= data.frame(a=1, b=2, c=3)
rbind(test, c(3,4,5))
  a b c
1 1 2 3
2 3 4 5
test= data.frame(matrix(ncol= 3, nrow= 0))
names(test) = c("a", "b", "c")
rbind(test, c(3,4,5))
  X3 X4 X5
1  3  4  5

Solution

  • As Dan Y points out, it's expected behaviour not a bug.

    data.table can do this

    library(data.table)
    
    # Create empty data.frame
    test <- data.frame(matrix(ncol= 3, nrow= 0))
    # Give it names
    names(test) <- c("a", "b", "c")
    
    # Coerce to data.table
    setDT(test)
    
    # rbind vector (set as a list)
    x <- rbind(test, as.list(c(3,4,5)), use.names = F, fill = F)
    
    # Coerce back to a data.frame if you wish
    setDF(x)
    
    x
    >  a b c
     1 3 4 5