Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
853 views
in Technique[技术] by (71.8m points)

r - Calculate means of specific columns

C1<-c(3,2,4,4,5)
C2<-c(3,7,3,4,5)
C3<-c(5,4,3,6,3)
DF<-data.frame(ID=c("A","B","C","D","E"),C1=C1,C2=C2,C3=C3)

DF
  ID Type C1 C2 C3
1  A    1  3  3  5
2  B    2  2  7  4
3  C    1  4  3  3
4  D    2  4  4  6
5  E    2  5  5  3

How do I calculate the mean of each column grouping by Type and ignore the ID column? Namely:

Type    C1   C2   C3
   1  3.50 3.00 4.00
   2  3.67 5.00 4.33

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Create the data with the Type column:

DF <- read.table(header=TRUE, text='  ID Type C1 C2 C3
1  A    1  3  3  5
2  B    2  2  7  4
3  C    1  4  3  3
4  D    2  4  4  6
5  E    2  5  5  3')

Then, with the knowledge that the ID column is at position 1, a simple application of aggregate gets you what you want:

aggregate(.~Type, data=DF[-1], FUN=mean)
  Type       C1       C2       C3
1    1 3.500000 3.000000 4.000000
2    2 3.666667 5.333333 4.333333

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.7k users

...