我想創建一個函數來合併名稱中包含已定義字符串的數據幀。在以下示例中,myfun(A)
將合併名稱包含「A」的數據幀,即A1
和A2
,並將B1
留出。按名稱合併數據幀使用R
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)])
我最好的嘗試(不工作):
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)
}
嘗試'減少(函數(...)合併(...,by ='id'),mget(ls(pattern ='A \\ d +')))' – akrun
@akrun,Spot on !非常感謝 – goclem
看起來像某種類型的[this]類型(http://stackoverflow.com/questions/8091303/simultaneously-merge-multiple-data-frames-in-a-list) –