Lin Ma - 1 year ago 169

R Question

I have data structure (data frame), which contains 3 column, age (integer), weight (float) and height (float), I want to calculate average and median weight/height in each age group (e.g. average weight/height in age 10, average weight/height in age 11, average weight/height in age 12, etc.). Wondering if there are any reference code examples?

Currently, I am doing group-by alike function outside R using Python numpy/pandas package. If there is R built-in solution for group-by, it will be great.

regards,

Lin

Answer Source

We can use `dplyr`

```
library(dplyr)
df1 %>%
group_by(age) %>%
summarise_each(funs(mean))
```

Or with `data.table`

```
library(data.table)
setDT(df1)[, lapply(.SD, mean), by = age]
```

Or using `aggregate`

from `base R`

```
aggregate(.~age, df1, mean)
```