I have five data frames from 60 columns that I need to combine. Each of them has the same columns, and I combine them with their means, since they represent the same meaning. The problem is not the possibility of combining them, but to do it effectively. Here is an example of data / code:
set.seed(123)
dat1 <- data.frame( a = rnorm(16), b = rnorm(16), c = rnorm(16), d = rnorm(16), e = rnorm(16), f = rnorm(16))
dat2 <- data.frame( a = rnorm(16), b = rnorm(16), c = rnorm(16), d = rnorm(16), e = rnorm(16), f = rnorm(16))
dat3 <- data.frame( a = rnorm(16), b = rnorm(16), c = rnorm(16), d = rnorm(16), e = rnorm(16), f = rnorm(16))
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))
)
head(final_data)
The problem is that I do not want to overwrite a=rowMeans(cbind(dat1$a,dat2$a,dat3$a))for each of the 60 columns in the new data frame. Can you come up with a good way to do this?
EDIT: I'm going to accept the following answer as it allows me to set columns for its application -
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