Skip to content

Instantly share code, notes, and snippets.

@jeremyyeo
Last active November 23, 2017 02:12
Show Gist options
  • Save jeremyyeo/bf4f158a7c5db0aacb482692297df05e to your computer and use it in GitHub Desktop.
Save jeremyyeo/bf4f158a7c5db0aacb482692297df05e to your computer and use it in GitHub Desktop.
# rbind uneven columns
# dummy data
x <- data.frame(name = "alice",
date = 1,
time = 3)
y <- data.frame(name = "bob",
time = 2)
print(x)
print(y)
# Usually there will be a dataframe with all required columns. So we just make
# the new dataframe have NA's where the required columns don't exist. You can
# also create a vector of all columns required as is the case here.
# Create the list of columns your end dataframe should have.
list_of_cols <- c("name", "rank", "date", "time")
add_missing_cols <- function(x, list) {
x[setdiff(list, names(x))] <- NA
return(x)
}
x <- add_missing_cols(x, list_of_cols)
y <- add_missing_cols(y, list_of_cols)
# rbind them.
xy <- rbind(x, y)
print(xy)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment