Skip to content

Instantly share code, notes, and snippets.

@Sleepingwell
Created September 27, 2013 10:03
Show Gist options
  • Save Sleepingwell/6726433 to your computer and use it in GitHub Desktop.
Save Sleepingwell/6726433 to your computer and use it in GitHub Desktop.
How to merge a list of data frames in R
# dummy data
maxN <- 10
listLen <- 6
Ns <- sample(as.integer(maxN/2):maxN, listLen)
dat <- lapply(Ns, function(N) data.frame(country=sample(maxN, N), var=rnorm(N)))
# function that (recursively) does the merging
merger <- function(lst, var.name) if(length(lst) == 1) lst else merge(lst[[1]], merger(lst[-1], var.name), by=var.name, all=T)
# do the merge and put sensible names on the result, and fix the NAs (set to zero)
merged <- merger(dat, 'country')
colnames(merged) <- paste('year', 1:length(dat), sep='')
merged[is.na(merged)] <- 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment