r - 基于所有其他字符列中的逐行字符串检测来改变条件列
问题描述
想象一下我有一个简单的小标题:
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 有一种简单的方法,但根本无法解决!
解决方案
rowSums
在基础 R 中使用:
cols <- sapply(df, is.character)
df$d <- ifelse(rowSums(sapply(df[cols], grepl, pattern = 'a')) > 0,
'present', 'absent')
With dplyr
,我们可以使用rowwise
with 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
推荐阅读
- subscription - Laravel Lighthouse,订阅时如何获取所有数组数据?
- javascript - 在反应中传递道具并显示在列表中的方式
- python - nn.MaxPool2d 与 nn.functional.max_pool2d 之间的区别?
- c# - 当我启动它时,我的表单打开然后关闭
- c - 为什么打印二维字符数组会产生垃圾值?
- batch-file - 如何在用户的桌面目录中创建目录?
- python - Pandas - 多数据框多列条件检查和分配
- arrays - 从 get() 的一维数组中查找矩阵大小
- python - 从 PySpark 数据框中选择随机行
- ios - 检测 iPhone 何时连接到车载蓝牙