I have the following data frame
x <- read.table(text = \" id1 id2 val1 val2
1 a x 1 9
2 a x 2 4
3 a y 3 5
4 a y 4
Another dplyr
option is across
which is part of current dev version
#devtools::install_github("tidyverse/dplyr")
library(dplyr)
x %>%
group_by(id1, id2) %>%
summarise(across(starts_with("val"), list(mean = mean, n = length)))
Result
# A tibble: 4 x 4
# Groups: id1 [2]
id1 id2 mean$val1 $val2 n$val1 $val2
1 a x 1.5 6.5 2 2
2 a y 3.5 7 2 2
3 b x 2 8 2 2
4 b y 3 6 2 2
packageVersion("dplyr")
[1] ‘0.8.99.9000’