首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将group_by和summarise_all结合使用?

如何将group_by和summarise_all结合使用?
EN

Stack Overflow用户
提问于 2019-06-20 21:31:31
回答 2查看 2.8K关注 0票数 2
代码语言:javascript
复制
   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. 总结,总结
  3. 对于所有其他列,我想通过只取第一个值来summarise_all
EN

回答 2

Stack Overflow用户

发布于 2019-06-20 21:36:45

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

代码语言:javascript
复制
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

样本数据:

代码语言:javascript
复制
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")
票数 5
EN

Stack Overflow用户

发布于 2019-06-20 21:49:48

代码语言:javascript
复制
library(tidyverse)
df <- tribble(~x, ~y,  # making a sample data frame
 1,  1,
 3,  2,
 2,  3,
 3,  4,
 2,  5,
 4,  6,
 5,  7,
 2,  8,
 1,  9,
 1, 10,
 3, 11,
 4, 12)

df <- df %>% 
  add_column(z = sample(1:nrow(df))) #add another column for the example

df


# If there is only one additional column and you need the first value
df %>% 
  group_by(x) %>% 
  summarise(sum_y = sum(y), z_1st = z[1])


# otherwise use summarise_at to address all the other columns
f <- function(x){x[1]} # function to extract the first value
df %>% 
  group_by(x) %>% 
  summarise_at(.vars = vars(-c('y')), .funs = f)  # exclude column y from the calculations
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56694150

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档