Summing down a column with multiple categories

51 views Asked by At

If I have a data frame that looks like

dat<-data.frame(val= c(1,2,3,4,5,6,7),category= c("A","B","c","A","B","c","D"))
dat

  val category
1   1        A
2   2        B
3   3        c
4   4        A
5   5        B
6   6        c
7   7        D

I'd like to AVERAGE by the category so the output looks like

A  2.5
B   3.5
C    4.5
D     7

What's the best way to do this?

1

There are 1 answers

1
Daniel Anderson On

The most straightforward way would be to use tapply as follows:

tapply(dat$val, dat$category, FUN = mean)

Note that if you have missing values you'd want to amend it to ignore those in the calculation of the mean

tapply(dat$val, dat$category, FUN = mean, na.rm = TRUE)

see ?tapply