-4

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?

josliber
  • 43,891
  • 12
  • 98
  • 133
user3022875
  • 8,598
  • 26
  • 103
  • 167
  • 1
    Take a look at [this answer](http://stackoverflow.com/a/16657546/1315767) – Jilber Urbina Jun 12 '15 at 23:01
  • 2
    Downvote for no research effort `r average by category` in google - first result is http://stats.stackexchange.com/questions/8225/how-to-summarize-data-by-group-in-r which would give you multiple answers. – thelatemail Jun 12 '15 at 23:46

1 Answers1

2

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

Daniel Anderson
  • 2,394
  • 13
  • 26
  • I'm not sure what is going on from your end. If I copy your `dat` argument exactly, on a fresh `R` session, and then run `tapply`, I get `2.5 3.5 4.5 7.0`. – Daniel Anderson Jun 12 '15 at 23:09