I have this df as an example
df = data.frame(x = c(rep(1,5),rep(2,5)),
y = 1:10,
z = 11:20)
and I wish to use lapply
with group_by%>%sum
so I have the following output
x y z
1 1 15 65
2 2 40 90
I have this df as an example
df = data.frame(x = c(rep(1,5),rep(2,5)),
y = 1:10,
z = 11:20)
and I wish to use lapply
with group_by%>%sum
so I have the following output
x y z
1 1 15 65
2 2 40 90
Here are 3 ways of doing it
library(dplyr)
# 1
df %>%
group_by(x) %>%
summarise(across(everything(), \(x) sum(x, na.rm = T))
# 2 (requires the new version of dplyr)
df %>%
summarise(across(everything(), \(x) sum(x, na.rm = T)), .by = x)
# 3 (deprecated, use with old versions of dplyr)
df %>%
group_by(x) %>%
summarise_all(\(x) sum(x, na.rm = T))
# A tibble: 2 × 3
x y z
<dbl> <int> <int>
1 1 15 65
2 2 40 90