Combining multiple data frames in a global environment into one file

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

Is this what I tried but it does not work? Any suggestion is welcome and appreciated.

flist=ls(pattern="propen") sapply(flist,function(x){merge(x,bmi,by="cfact",all.x=T)}) 
+5
source share
1 answer

If you have several related data frames, the best of them all is on the list, and not all of them in the global environment. Based on your application

They are called propens1, propens2, propens3 and propens4

we can collect all your data frames using

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

Then, since you need four frames of data as a result, all we need to do is run merge() for each of them. Now that we have the data frames in the list, we can easily do this with lapply() .

 lapply(datalist, merge, y = bmi, by = "cfact", all.x = TRUE) 
+6
source

Source: https://habr.com/ru/post/1236475/


All Articles