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

后端 未结 9 1781
野的像风
野的像风 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 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.

提交回复
热议问题