英文:
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)
我希望使用lapply
和group_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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论