假设我有一个简单的tibble:
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都有一种简单的方法,但是根本就不能解决!
发布于 2021-02-23 18:13:13
在base R中使用rowSums:
cols <- sapply(df, is.character)
df$d <- ifelse(rowSums(sapply(df[cols], grepl, pattern = 'a')) > 0,
'present', 'absent')通过dplyr,我们可以将rowwise与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 https://stackoverflow.com/questions/66331074
复制相似问题