在R中有没有一种方法可以检查一列中的值是否包含另一列中的值?在下面的示例中,我试图查看模式中的值是否包含在col1中的值中(独立于每行),但得到一条警告消息:"argument‘col2’has length >1 and only the first element will be used“。标志列第一行/最后一行应显示“是”,第二行和第三行应显示“否”。任何关于如何解决的想法都将不胜感激。
col1 <- c("R.S.U.L.C","S.I.W","P.U.E","A.E.N")
col2 <- c("R","U","I","N")
df2 <- data.frame(col1,col2)
df2$Flag <- ifelse(grepl(df2$col2,df2$col1),"Yes","No")
发布于 2020-04-29 15:42:50
这可以通过组合使用sapply/grepl
来完成。循环遍历df2$col
并在grepl
df$col1
中对其进行遍历。
这一行很明显。
i <- sapply(seq_along(df2$col2), function(i) grepl(df2$col2[i], df2$col1[i]))
df2$Flag <- c("No", "Yes")[i + 1L]
df2
# col1 col2 Flag
#1 R.S.U.L.C R Yes
#2 S.I.W U No
#3 P.U.E I No
#4 A.E.N N Yes
发布于 2020-04-29 15:45:02
df2$flag <- mapply(grepl, df2$col2, df2$col1)
grepl()
的pattern参数只使用第一个元素:
请参阅?grepl
如果提供长度为2或更大的字符向量,则第一个元素将与警告一起使用。
发布于 2020-04-29 18:26:08
我们可以使用str_detect
,它对模式和字符串都是矢量化的
library(dplyr)
library(stringr)
df2 <- df2 %>%
mutate(Flag = c('No', 'Yes')[1+str_detect(col1, as.character(col2))])
df2
# col1 col2 Flag
#1 R.S.U.L.C R Yes
#2 S.I.W U No
#3 P.U.E I No
#4 A.E.N N Yes
https://stackoverflow.com/questions/61505466
复制相似问题