cbind a dataframe with an empty dataframe - cbind.fill?

后端 未结 9 1646
野的像风
野的像风 2020-11-22 11:25

I think I\'m looking for an analog of rbind.fill (in Hadley\'s plyr package) for cbind. I looked, but there is no cbind.fill

相关标签:
9条回答
  • 2020-11-22 11:56

    While, I think Tyler's solution is direct and the best here, I just provide the other way, using rbind.fill() that we already have.

    require(plyr) # requires plyr for rbind.fill()
    cbind.fill <- function(...) {                                                                                                                                                       
      transpoted <- lapply(list(...),t)                                                                                                                                                 
      transpoted_dataframe <- lapply(transpoted, as.data.frame)                                                                                                                         
      return (data.frame(t(rbind.fill(transpoted_dataframe))))                                                                                                                          
    } 
    
    0 讨论(0)
  • 2020-11-22 11:58

    We can use a list instead of data.frame and convert it to a data.frame at the end. For instance:

    df = list()
    df2 = data.frame(col1 = 1:3, col2 = c('a','b','c'))
    df = as.data.frame(cbind(df, as.matrix(df2)))
    df
    
    #   col1 col2
    # 1    1    a
    # 2    2    b
    # 3    3    c
    
    0 讨论(0)
  • 2020-11-22 11:59

    cbind.na from the qpcR package can do that.

        install.packages("qpcR")
        library(qpcR)
        qpcR:::cbind.na(1, 1:7)
    
    0 讨论(0)
  • 2020-11-22 12:02

    Using rowr::cbind.fill

    rowr::cbind.fill(df1,df2,fill = NA)
       A B
    1  1 1
    2  2 2
    3  3 3
    4  4 4
    5  5 5
    6 NA 6
    
    0 讨论(0)
  • 2020-11-22 12:05

    When a and b are data frames, following should work just fine:

    ab <- merge(a, b, by="row.names", all=TRUE)[,-1]
    

    or another possibility:

    rows <- unique(c(rownames(a), rownames(b)))
    ab <- cbind(a[rows ,], b[rows ,])
    
    0 讨论(0)
  • 2020-11-22 12:07

    I just find a trick that when we want to add columns into an empty dataframe, just rbind it at first time, than cbind it later.

        newdf <- data.frame()
        # add the first column
        newdf <- rbind(newdf,data.frame("col1"=c("row1"=1,"row2"=2)))
        # add the second column
        newdf <- cbind(newdf,data.frame("col2"=c("row1"=3,"row2"=4)))
        # add more columns
        newdf <- cbind(newdf,data.frame("col3"=c("row1"=5,"row2"=6)))
        # result
        #     col1 col2 col3
        #row1    1    3    5
        #row2    2    4    6
    

    I don't know why, but it works for me.

    0 讨论(0)
提交回复
热议问题