Lin Ma Lin Ma - 1 year ago 227
R Question

group by average in R

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.


Answer Source

We can use dplyr

df1 %>%
     group_by(age) %>%

Or with data.table

setDT(df1)[, lapply(.SD, mean), by = age]

Or using aggregate from base R

aggregate(.~age, df1, mean)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download