【问题标题】:How to select the specific rows using dplyr package in R?如何使用 R 中的 dplyr 包选择特定行?
【发布时间】:2022-08-02 17:01:04
【问题描述】:

如何使用 R 中的 dplyr 包选择特定行? 如果column1是NA,我想得到column2的值,如果column2是NA,我想得到column1的值。

(示例代码)

test_data %>% 
  select(Column1, Column2) %>% 
  **?????**

(例子)

测试数据

(Column1)|(Column2)
NA|20
NA|30
10|NA
40|NA

结果

(Column)
      20
      30
      10
      40

    标签: r dplyr


    【解决方案1】:

    您正在寻找的功能是coalesce

    library(dplyr)
    
    test_data %>% transmute(col3 = coalesce(col1, col2))
    
      col3
    1   20
    2   30
    3   10
    4   40
    

    数据

    structure(list(col1 = c(NA, NA, 10L, 40L), col2 = c(20L, 30L, 
    NA, NA)), class = "data.frame", row.names = c(NA, -4L))
    

    【讨论】:

      【解决方案2】:

      另一种方法是使用pmin

      library(dplyr)
      df %>% 
        transmute(col3  = pmin(col1, col2, na.rm = T))
      
      #   col3
      # 1   20
      # 2   30
      # 3   10
      # 4   40
      
      structure(list(col1 = c(NA, NA, 10L, 40L), col2 = c(20L, 30L, 
      NA, NA)), class = "data.frame", row.names = c(NA, -4L)) -> df
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-02
        • 2016-04-04
        • 1970-01-01
        • 2015-05-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多