I want to create a function that merges dataframes whose names contain a defined character string. In the following example, myfun(A)
would merge the dataframes whose name contains "A", that is, A1
and A2
, leaving B1
out.
A1=data.frame(id=paste0("id",1:10),var1=letters[sample(1:26,10)])
A2=data.frame(id=paste0("id",1:10),var2=LETTERS[sample(1:26,10)])
B1=data.frame(id=paste0("id",1:10),var3=letters[sample(1:26,10)])
My best try (which does not work):
myfun=function(my.pattern){
dfs=ls(,pattern=paste(my.pattern)) # Getting the list of dataframes whose name contains the pattern
merged_df=merge(dfs[1],dfs[2],by=id) # Merging those dataframes
return(merged_df)
}