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

后端 未结 9 1653
野的像风
野的像风 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:11

    We could add id column then use merge:

    df1 <- mtcars[1:5, 1:2]
    #                    mpg cyl id
    # Mazda RX4         21.0   6  1
    # Mazda RX4 Wag     21.0   6  2
    # Datsun 710        22.8   4  3
    # Hornet 4 Drive    21.4   6  4
    # Hornet Sportabout 18.7   8  5
    
    df2 <- mtcars[6:7, 3:4]
    #            disp  hp
    # Valiant     225 105
    # Duster 360  360 245
    
    #Add id column then merge
    df1$id <- seq(nrow(df1)) 
    df2$id <- seq(nrow(df2)) 
    
    merge(df1, df2, by = "id", all.x = TRUE, check.names = FALSE)
    #   id  mpg cyl disp  hp
    # 1  1 21.0   6  225 105
    # 2  2 21.0   6  360 245
    # 3  3 22.8   4   NA  NA
    # 4  4 21.4   6   NA  NA
    # 5  5 18.7   8   NA  NA
    

提交回复
热议问题