问题描述:

I want to compare two columnnames from two data frames and create a new table with the matched columnnames from the original data frames.

a<-data.frame(a1=c(1,2,3,4,5),a2=c(2,3,4,5,6),b1=c(3,4,5,6,7),c1=c(4,5,6,7,8))

b<-data.frame(c1=c(10,20,30,40,50),b1=c(20,30,40,50,60),d1=c(30,40,50,60,70))

I want to make a new dataframe adding a+b when the column names (e.g. 'c1' etc.) match. E.g. my new dataframe named 'c' will now be like this based on the above data:

c=data.frame(c1=c(10+4,20+5,30+6,40+7,50+8), b1=c(20+3,30+4,40+5,50+6,60+7))

My original dataframe is much larger than the above, so I was using 'for (i in 1:10)'. But it works only when both columnnames are in the same order in both dataframes.

Thanks on advance for your help.

网友答案:
as.data.frame(lapply(intersect(names(a), names(b)), 
              function(name) a[name] + b[name]))
网友答案:

the simpler way I can think is

c <- cbind(b[, which(colnames(b)%in% colnames(a))],
    a[, which(colnames(a)%in% colnames(b))])

is that what you was looking for?

cheers

相关阅读:
Top