我有多个列,其中有类似的数据,我有多个单词,我想知道它们是否在其中一个列中. 举个例子:
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的选项,但这不适用于我想要查找多个单词的事实(我try 了%in%Typeo),以及它不仅以我的模式开头,而且可以包含它(M0_TTT,TTT_M0,等等).
它可以是一个base-R或dummy的解决方案,这不是一个问题