Skip to content

Instantly share code, notes, and snippets.

@dreidpath
Created October 11, 2015 03:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dreidpath/9e290205519c420d7998 to your computer and use it in GitHub Desktop.
Save dreidpath/9e290205519c420d7998 to your computer and use it in GitHub Desktop.
Merge multiple dataframes into a single "flat file"
#############################################################################
# Two functions to merge a series of dataframes. This is needed if you want #
# to create a single "flat file" from multiple dataframes. #
#############################################################################
# Create an infix function %<<% that will merge two data frames.
# Note Bene:
# the dataframes to merge must have a shared column with the matched unique
# id named "id". You can vary this name by altering the code on line 12.
#
`%<<%` <- function(df1, df2){
merge(df1, df2, by="id") # Call the standard merge() function
}
mergeAll <- function(list_of_DFs){
if(length(list_of_DFs) < 2){ # Check at least two dataframes to merge
stop("There must be at least one dataframe for the function to work")
}
# Create a long string of all the dataframes to be merged, separating them
# by the newly created infix function (%<<%)
merge_command <- paste(list_of_DFs, collapse =' %<<% ')
# Evaluate the expression
eval(parse(text = merge_command))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment