Shunzhe Yao
Shunzhe Yao

Reputation: 31

calculate multiple columns mean in R and generate a new table

I have a data set in .csv. It contains multiple columns for example.

Group Wk1 WK2 WK3 WK4 WK5 WK6 
   A   1   2   3   4   5   6
   B   7   8   9   1   2   3
   C   4   5   6   7   8   9
   D   1   2   3   4   5   6

Then if I want to have the mean of both WK1 & WK2, Wk3, WK4 & WK5, WK6. How can I do that? The result may like

Group 1    2    3    4
mean  3.75 5.25 4.5  6

And how can I save it into a new table?

Thanks in advance.

Upvotes: 1

Views: 4957

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193677

You can melt your data.frame, create your groups using some basic indexing, and use aggregate:

library(reshape2)
X <- melt(mydf, id.vars="Group")
Match <- c(Wk1 = 1, Wk2 = 1, Wk3 = 2, Wk4 = 3, Wk5 = 3, Wk6 = 4)
aggregate(value ~ Match[X$variable], X, mean)
#   Match[X$variable] value
# 1                 1  3.75
# 2                 2  5.25
# 3                 3  4.50
# 4                 4  6.00

tapply is also an appropriate candidate here:

tapply(X$value, Match[X$variable], mean)
#    1    2    3    4 
# 3.75 5.25 4.50 6.00 

Upvotes: 2

Related Questions