userJT
userJT

Reputation: 11934

R: Is there a good replacement for plyr::rbind.fill in dplyr?

for tidyverse users, dplyr is the new way to work with data.

For users trying to avoid older package plyr, what is the equivalent function to rbind.fill in dplyr?

Upvotes: 43

Views: 13841

Answers (3)

rubengavidia0x
rubengavidia0x

Reputation: 590

Same Thing with R Base:

df2 <- data.frame(a = c(1:5), b = c(6:10))
df3 <- data.frame(a = c(11:15), b = c(16:20), c = LETTERS[1:5])
df2[setdiff(names(df3), names(df2))] <- NA
df3[setdiff(names(df2), names(df3))] <- NA

rbind(df2, df3)

Upvotes: 0

sashahafner
sashahafner

Reputation: 454

An alternative:

rbindf <- function(...) {
  
  l <- list(...)
  if(length(l) == 1) l <- l[[1]]
  nn <- length(l)

  x <- l[[1]]
  if(length(l)>1){
      for(i in 2:nn) {
        y <- l[[i]]
        if(nrow(x) > 0 & nrow(y) > 0) {
          if(!all(yinx <- names(y) %in% names(x))) {
            x[, names(y)[!yinx]] <- NA
          } 
          if(!all(xiny <- names(x) %in% names(y))) {
             y[, names(x)[!xiny]] <- NA
          } 
        }
        x <- rbind(x, y)
      }
  }
  return(x)
}

From https://github.com/sashahafner/biogas (originally from https://github.com/jonkatz2/monitoR).

Upvotes: 0

userJT
userJT

Reputation: 11934

Yes. dplyr::bind_rows

Credit goes to commenter.

Upvotes: 51

Related Questions