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)})
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With