gpt4 book ai didi

r - 如何将 group_by 与 summarize 和 summarise_all 一起使用?

转载 作者:行者123 更新时间:2023-12-05 09:13:08 25 4
gpt4 key购买 nike

   x  y
1 1 1
2 3 2
3 2 3
4 3 4
5 2 5
6 4 6
7 5 7
8 2 8
9 1 9
10 1 10
11 3 11
12 4 12

以上为部分输入

假设它还有一堆其他列

我想:

  1. group_by x
  2. 总结y
  3. 对于所有其他列,我想通过只取第一个值来 summarise_all

最佳答案

这是一种将其分解为两个问题并将它们结合起来的方法:

library(dplyr)
left_join(
# Here we want to treat column y specially
df %>%
group_by(x) %>%
summarize(sum_y = sum(y)),
# Here we exclude y and use a different summation for all the remaining columns
df %>%
group_by(x) %>%
select(-y) %>%
summarise_all(first)
)

# A tibble: 5 x 3
x sum_y z
<int> <int> <int>
1 1 20 1
2 2 16 3
3 3 17 2
4 4 18 2
5 5 7 3

示例数据:

df <- read.table(
header = T,
stringsAsFactors = F,
text="x y z
1 1 1
3 2 2
2 3 3
3 4 4
2 5 1
4 6 2
5 7 3
2 8 4
1 9 1
1 10 2
3 11 3
4 12 4")

关于r - 如何将 group_by 与 summarize 和 summarise_all 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56694150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com