Rose
Rose

Reputation: 53

How to get this result with aggregate in R

A small but useful sample as follows:

df=read.table(text="class time
        a 12
        a  11
        a 11
        b 15
        b 10
        c 14
        c 11
        ",header=TRUE)

I want to get the median for a and b together, this gives me a value of 11.

My effort is:

aggergate(time~class, data=df, median)

Upvotes: 0

Views: 48

Answers (1)

Rory S
Rory S

Reputation: 1298

I realise you asked specifically for a solution using aggregate, but there are a few ways to solve this problem that I find easier than using aggregate. The first, as Greg already suggested, would be something like:

median(df$time[df$class %in% c("a", "b")])

[1] 11

Alternatively, if you wanted to use a tidyverse approach, you could do:

library(tidyverse)
filter(df, class %in% c("a", "b")) %>% summarise(median(time))

  median(time)
1           11

Upvotes: 1

Related Questions