i have 5 dataframes of 60 columns need combine. each have same columns , i'm combining them means since represent same value. issue isn't ability combine them, doing efficiently. here sample data/code:
#reproducible random data set.seed(123) dat1 <- data.frame( = rnorm(16), b = rnorm(16), c = rnorm(16), d = rnorm(16), e = rnorm(16), f = rnorm(16)) dat2 <- data.frame( = rnorm(16), b = rnorm(16), c = rnorm(16), d = rnorm(16), e = rnorm(16), f = rnorm(16)) dat3 <- data.frame( = rnorm(16), b = rnorm(16), c = rnorm(16), d = rnorm(16), e = rnorm(16), f = rnorm(16)) #this works inefficient final_data<-data.frame(a=rowmeans(cbind(dat1$a,dat2$a,dat3$a)), b=rowmeans(cbind(dat1$b,dat2$b,dat3$b)), c=rowmeans(cbind(dat1$c,dat2$c,dat3$c)), d=rowmeans(cbind(dat1$d,dat2$d,dat3$d)), e=rowmeans(cbind(dat1$e,dat2$e,dat3$e)), f=rowmeans(cbind(dat1$f,dat2$f,dat3$f)) ) #what results should head(final_data) # b c d e f # 1 0.573813625 0.17695841 -0.1434628 -0.53673101 0.353906578 0.24262067 # 2 0.135689926 -0.69206908 0.2888584 -0.37215810 -0.038298083 -0.23317107 # 3 0.004068807 0.44666945 0.5205118 0.09587453 -0.308528454 0.30516883 # 4 0.347100292 0.02401646 0.1409754 -0.15931120 0.587047386 -0.08684867 # 5 0.006529998 0.09010946 0.4932670 0.62606230 -0.005235813 -0.36967000 # 6 0.240225778 -0.45824825 -0.5000004 0.66131121 0.619480608 0.55650611
the issue here don't want rewrite a=rowmeans(cbind(dat1$a,dat2$a,dat3$a))
each of 60 columns in new data frame. can think of way go this?
edit: i'm going accept following answer since allows me set columns apply over-
final_data1<-as.data.frame(sapply(colnames(dat1),function(i) rowmeans(cbind(dat1[,i],dat2[,i],dat3[,i])))) > identical(final_data1,final_data) [1] true
try this:
sapply(colnames(dat1),function(i) rowmeans(cbind(dat1[,i],dat2[,i],dat3[,i])))