【问题标题】:How to combine scattered values into one row using R如何使用R将分散的值组合成一行
【发布时间】:2022-10-18 22:48:36
【问题描述】:

我有一个这样的数据集,我想要如下所需的数据集。

    dat <- read.table(text="Id  Bug    Drug1 Drug2 
A   Staph     NA  S
A   Staph  S  NA
A   E.coli    NA  S
A   E.coli  S  NA", header=TRUE)


dat.desired <- read.table(text="Id  Bug    Drug1 Drug2 
A   Staph     S  S
A   E.coli    S  S", header=TRUE)

【问题讨论】:

    标签: r multiple-columns summarize


    【解决方案1】:

    以下应该有效:

    dat %>% 
      group_by(Id, Bug) %>% 
      summarise(across(Drug1:Drug2, ~.x[!is.na(.x)][1]))
    

    输出:

    #  Id    Bug    Drug1 Drug2
    # <chr> <chr>  <chr> <chr>
    # 1 A     E.coli S     S    
    # 2 A     Staph  S     S   
    

    【讨论】:

      猜你喜欢
      • 2020-11-05
      • 1970-01-01
      • 2021-10-01
      • 1970-01-01
      • 2020-06-30
      • 2021-11-26
      • 1970-01-01
      • 2015-07-01
      • 2019-01-18
      相关资源
      最近更新 更多