[英]R Column Check if Contains Value from Another Column
R 中有沒有辦法檢查一列中的值是否包含另一列中的值? 在下面的示例中,我試圖查看 col2 中的值是否包含在 col1 中的值中(獨立地包含在每一行中)但收到一條警告消息:“argument 'pattern' 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")
這可以通過sapply/grepl
的組合來完成。 沿着df2$col
循環並在字符串df$col1
中對其進行grepl
。
單行是顯而易見的。
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
df2$flag <- mapply(grepl, df2$col2, df2$col1)
grepl()
的模式參數只使用第一個元素:
見?grepl
:
如果提供長度為 2 或更大的字符向量,則使用第一個元素並發出警告。
我們可以使用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
使用ifelse
的str_detect
的整潔實現。 請注意,使用fixed()
可確保文字內容匹配。 否則, str_detect
默認為正則表達式,如果模式列包含可解釋為正則表達式的字符,這可能會導致意外行為。
library(tidyverse)
df2 <- df2 %>%
mutate(Flag = ifelse(str_detect(col1, fixed(as.character(col2))), "Yes", "No"))
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.