0

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
Julien
  • 1,613
  • 1
  • 10
  • 26
Anas116
  • 797
  • 2
  • 9

1 Answers1

3

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
Julien
  • 1,613
  • 1
  • 10
  • 26
  • and if I had missing values and I wish to include the argument na.rm in the function sum. How can I make that happen ? – Anas116 Feb 23 '23 at 14:59