首页 > 解决方案 > 基于所有其他字符列中的逐行字符串检测来改变条件列

问题描述

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

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 有一种简单的方法,但根本无法解决!

标签: rdictionarydplyr

解决方案


rowSums在基础 R 中使用:

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

With dplyr,我们可以使用rowwisewith c_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 

推荐阅读