【问题标题】:mutate conditional column based on rowwise string detection in all other character columns基于所有其他字符列中的逐行字符串检测来改变条件列
【发布时间】:2021-02-23 10:09:33
【问题描述】:

想象一下我有一个简单的小标题:

tribble(~a,~b,~c,
        1, "def", "abc",
        2, "def", "def")

我想改变一个新列“d”,其值取决于字符串是否存在于所有其他列中。在这种情况下,我正在寻找字符串“abc”。最终输出如下所示:

tribble(~a,~b,~c,~d,
        1, "def", "abc", "present",
        2, "def", "def", "absent")

实际上,我的 tibble 有大约 20 列,其中可能有 10 列是字符,而我要查找的字符串更复杂,例如 "[Aa]|[Cc]"。我确信 pmap、case_when 和 str_detect 有一种简单的方法,但根本无法解决!

【问题讨论】:

    标签: r dictionary dplyr


    【解决方案1】:

    在基础 R 中使用 rowSums

    cols <- sapply(df, is.character)
    df$d <- ifelse(rowSums(sapply(df[cols], grepl, pattern = 'a')) > 0, 
                   'present', 'absent')
    

    使用dplyr,我们可以使用rowwisec_across

    library(dplyr)
    library(stringr)
    
    df %>%
      rowwise() %>%
      mutate(d = if(any(str_detect(c_across(where(is.character)), 'a'))) 
                    'present' else 'absent')
    
    #      a   b     c     d      
    #  <dbl> <chr> <chr> <chr>  
    #1     1 def   abc   present
    #2     2 def   def   absent 
    

    【讨论】:

    • 谢谢!抱歉,我应该更清楚字符串只是部分的,这就是我想 str_detect 的原因。所以在上述情况下可能只是我们正在寻找的“a”。如果它可以推广到所有字符列而不是必须命名它们,那也很棒。
    猜你喜欢
    • 2019-11-27
    • 2021-02-28
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多