我有一个如下所示的数据框,所需的输出如下所示。
df <- data.frame(
col1 = c("abc_1_102", "abc_1_103", "xyz_1_104")
)
selection <- data.frame(col1 =c("abc", "xyz"),col2 =c("102", "106"))
所需输出
col1 col9
1 abc_1_102 SELECT
2 abc_1_103 NOTSELECT
3 xyz_1_104 NOTSELECT
我们如何使用 R 中的 grepl() 函数来实现这一点
我尝试了什么?
df$col2 <- ifelse(grepl(paste("^", selection$col1, "$", collapse = "|"), df$col1)&
grepl(paste("^", selection$col2, "$", collapse = "|"), df$col1),
"SELECT", "NOTSELECT")
print(df)
col1 col2
1 abc_1_102 NOTSELECT
2 abc_1_103 NOTSELECT
3 xyz_1_104 NOTSELECT
这里,结果不正确,因为在选择中,column1和column2中的值与df第1行中value的第一个和第三个元素匹配。
df$col9 <- ifelse(grepl(paste(selection$col1, selection$col2, sep = "_1_", collapse = "|"), df$col1), "SELECT", "NOTSELECT")