【问题标题】:How to use summarise to take the value of an variable that corresponds to the max. value of another variable?如何使用 summarise 获取对应于最大值的变量的值。另一个变量的值?
【发布时间】:2021-08-07 09:25:09
【问题描述】:

如何使用summary取一个变量的值对应另一个变量的最大值?

数据:我在下面有一个简化的数据集。

df <- read.table(text = "
                 ID SBP DATE
                 1 90 20210102
                 1 106 20210111
                 2 80 20210513
                 2 87 20210513
                 2 88 20210413", header = TRUE)

我希望取SBP 的值,它对应于最新的DATE(即最近测量的收缩压)。可能存在平局,即在同一天 > 1 次测量(如ID=2 所示),在这种情况下,我想采取第一行。除此之外,我可能需要获取其他变量,例如 SBP 的平均值,不。 SBP 等的测量值。因此,我只想使用summarise()。以下是所需的输出。

期望的输出

df <- read.table(text = "
                 ID SBP 
                 1 106 
                 2 80", header = TRUE)

这是我之前所做的。

1)summarise[which.max 一起使用

df %>% group_by(ID) %>% summarise(SBP = SBP[which.max(DATE)])
## A tibble: 2 x 2
#     ID   SBP
#  <int> <int>
#1     1   106
#2     2    80

2) 使用slice_max

df %>% group_by(ID) %>% slice_max(DATE, with_ties = FALSE)
## A tibble: 2 x 2
#     ID   SBP
#  <int> <int>
#1     1   106
#2     2    80

3)summariselast 一起使用

df %>% group_by(ID) %>% summarise(SBP = last(SBP, DATE))
## A tibble: 2 x 2
#     ID   SBP
#  <int> <int>
#1     1   106
#2     2    87

我认为(3)在可读性方面是理想的,但不是采用第一个行项目,而是采用最后一个行项目(不是我想要的)。如果我使用 (2),在使用 slice_max 之前,我必须使用 mutate 来创建其他感兴趣的变量(如测量次数、平均值等)。 (1) 会让其他 R 读者/用户感到困惑。

我的问题:我怎样才能写出类似 (3) 的内容,但在有关系的情况下使用第一行?

【问题讨论】:

    标签: r dplyr tidyverse tidyr data-manipulation


    【解决方案1】:

    我会使用 1) arrange + distinct 或 2) group_by + summarise + first 。第一种方法可读性不强,但对于大数据集,它实际上比使用 group by 性能更高。

    library(tidyverse)
    
    df %>%
      arrange(ID, -DATE) %>% 
      distinct(ID, .keep_all = TRUE)
    #>   ID SBP     DATE
    #> 1  1 106 20210111
    #> 2  2  80 20210513
    
    
    df %>% 
      group_by(ID) %>% 
      summarise(
        SBP = first(SBP, -DATE)
      )
    #> # A tibble: 2 x 2
    #>      ID   SBP
    #> * <int> <int>
    #> 1     1   106
    #> 2     2    80
    

    reprex package (v1.0.0) 于 2021-05-18 创建

    【讨论】:

    • 两种情况下的-DATE 是否与desc(DATE) 相似?
    • 是的,应该类似:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 2015-03-19
    • 1970-01-01
    相关资源
    最近更新 更多