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

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

    Here's a cbind fill:

    cbind.fill <- function(...){
        nm <- list(...) 
        nm <- lapply(nm, as.matrix)
        n <- max(sapply(nm, nrow)) 
        do.call(cbind, lapply(nm, function (x) 
            rbind(x, matrix(, n-nrow(x), ncol(x))))) 
    }
    

    Let's try it:

    x<-matrix(1:10,5,2)
    y<-matrix(1:16, 4,4)
    z<-matrix(1:12, 2,6)
    
    cbind.fill(x,y)
    cbind.fill(x,y,z)
    cbind.fill(mtcars, mtcars[1:10,])
    

    I think I stole this from somewhere.

    EDIT STOLE FROM HERE: LINK

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 12:19

    I suggest a modification of Tyler's answer. My function allows cbind-ing of data.frames and/or matrices with vectors without loosing column names as it happens in Tyler's solution

    cbind.fill <- function(...){
      nm <- list(...) 
      dfdetect <- grepl("data.frame|matrix", unlist(lapply(nm, function(cl) paste(class(cl), collapse = " ") )))
      # first cbind vectors together 
      vec <- data.frame(nm[!dfdetect])
      n <- max(sapply(nm[dfdetect], nrow)) 
      vec <- data.frame(lapply(vec, function(x) rep(x, n)))
      if (nrow(vec) > 0) nm <- c(nm[dfdetect], list(vec))
      nm <- lapply(nm, as.data.frame)
    
      do.call(cbind, lapply(nm, function (df1) 
        rbind(df1, as.data.frame(matrix(NA, ncol = ncol(df1), nrow = n-nrow(df1), dimnames = list(NULL, names(df1))))) )) 
    }
    
    cbind.fill(data.frame(idx = numeric()), matrix(0, ncol = 2), 
               data.frame(qwe = 1:3, rty = letters[1:3]), type = "GOOD", mark = "K-5")
    #       idx V1 V2 qwe rty type mark
    #     1  NA  0  0   1   a GOOD  K-5
    #     2  NA NA NA   2   b GOOD  K-5
    #     3  NA NA NA   3   c GOOD  K-5
    
    0 讨论(0)
提交回复
热议问题