如何在lapply中使用group_by%>%sum?

huangapple go评论60阅读模式
英文:

how to use group_by%>%sum in lapply?

问题

我有这个数据框作为示例

df = data.frame(x = c(rep(1,5),rep(2,5)),
                y = 1:10,
                z = 11:20)

我希望使用lapplygroup_by%>%sum来获得以下输出

  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

答案1

得分: 3

以下是翻译好的代码部分:

1

library(dplyr)
# 1
df %>%
  group_by(x) %>%
  summarise(across(everything(), \(x) sum(x, na.rm = T))

2 (需要新版本的dplyr)

df %>%
  summarise(across(everything(), \(x) sum(x, na.rm = T)), .by = x)

3 (已不推荐,适用于旧版本的dplyr)

df %>%
  group_by(x) %>%
  summarise_all(\(x) sum(x, na.rm = T))

A tibble: 2 × 3
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

huangapple
  • 本文由 发表于 2023年2月23日 21:51:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75545719.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定