Created
September 27, 2013 10:03
-
-
Save Sleepingwell/6726433 to your computer and use it in GitHub Desktop.
How to merge a list of data frames in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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