Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merging multiple data frames in the global environment to one file

Tags:

merge

r

I have 4 dataframes in my global environment. They are named propens1, propens2, propens3 and propens4. I have a 5th file, that is named "bmi" and I want to merge bmi with all of the four propen files. I can merge them individually using dplyr joins or base merge, but I was wondering if there was a way to merge it with a single statement instead of 4.

This is what I have tried, but it doesn't work? Any suggestion is welcomed and appreciated.

flist=ls(pattern="propen")
sapply(flist,function(x){merge(x,bmi,by="cfact",all.x=T)})
like image 459
R User Avatar asked Nov 20 '15 22:11

R User


1 Answers

If you have multiple related data frames, it is best to have them all in a list instead of having them all separate in the global environment. Based on your statement

They are named propens1, propens2, propens3 and propens4

we can gather all your data frames with

datalist <- mget(ls(pattern = "propens[1-4]"))

Then since you want four data frames in the result, all we have to do is run merge() on each one of those. Now that we have the data frames in a list, we can do that easily with lapply().

lapply(datalist, merge, y = bmi, by = "cfact", all.x = TRUE)
like image 76
Rich Scriven Avatar answered Oct 25 '22 22:10

Rich Scriven