在 R 中查找多列中的字符串

问题描述 投票:0回答:1

我有多个列,其中包含相似的数据,并且我有多个单词,我想知道它们是否在其中一列中。 举个例子:

df = data.frame(ttt1= c("METO","LETO","META","LETA","METO"),
                ttt2=c("LETO","","METO","","LETA"))
df
  ttt1 ttt2
1 METO LETO
2 LETO     
3 META METO
4 LETA     
5 METO LETA

我想从那些以“ttt”开头或包含“ttt”的列中,以这种方式创建列:

df2 <- df %>%
  mutate(cl_m = ifelse(ttt1 %in% c("METO", "META") | ttt2 %in% c("METO", "META"), 1, 0),
         cl_l = ifelse(ttt1 %in% c("LETO", "LETA") | ttt2 %in% c("LETO", "LETA"), 1, 0))
df2
  ttt1 ttt2 cl_m cl_l
1 METO LETO    1    1
2 LETO         0    1
3 META METO    1    0
4 LETA         0    1
5 METO LETA    1    1

我发现了一些带有一些基本R的选项https://copyprogramming.com/howto/check-string-in-columns-r-code-example但这并不适用于我想查找多个单词的事实(我尝试了 %in% 拼写错误),事实上它不仅以我的模式开头,而且可以包含它(m0_ttt、ttt_m0 等..)

它可以是一个base-R或dplyr解决方案,这不是问题

r string dplyr
1个回答
0
投票

dplyr
中,您可以
mutate
并使用
across
来测试列是否包含感兴趣的字符串。使用
rowSums
来总结实例数。一个小窍门是使用
sign()
将总和转换为 1 或 0 而不是
+(... > 1)
:

library(dplyr)
df %>%
  mutate(cl_m = sign(rowSums(across(contains("ttt"), ~ +(.x %in% c("METO", "META"))))),
         cl_l = sign(rowSums(across(contains("ttt"), ~ +(.x %in% c("LETO", "LETA"))))))

输出:

#   ttt1 ttt2 cl_m cl_l
# 1 METO LETO    1    1
# 2 LETO         0    1
# 3 META METO    1    0
# 4 LETA         0    1
# 5 METO LETA    1    1
© www.soinside.com 2019 - 2024. All rights reserved.