用Rpply匹配R中的两个字符向量

时间:2013-06-13 11:28:34

标签: r vector match

我想匹配来自两个字符向量的项目“A”和“B”,两个找出两件事:1)向量A中的项是否出现在向量B中(是/否)和2)来自向量的项目B不出现在载体A?

这两个向量看起来像这样:

A <- c("i", "u", "I", "U", "E", "V", "@", "{", "$", "#", "Q", "1", "2", "3", "4", "5", "6", "7", "8", "9")
B <- c("1", "1", "1", "1", "#", "$", "$", "1", "2", "2", "1", "d", "d", "i", "i", "i", "i", "1", "3", "2", "2", "F", "2", "2", "2", "5", "5", "5", "@", "5", "6", "5", "z", "z", "S", "S")

我可以用这个函数部分回答我的第一个问题:

test_match <- function(item_vector_A, item_vector_B){
ifelse(item_vector_A == item_vector_B, print(1), print(0))
}

lapply(A, B, FUN = test_match) -> results

但是,当我尝试这个时,我会得到一个功能列表:

lapply(A, B, FUN = test_match) -> results
results
[[1]]
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[[2]]
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[[3]]
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
#etc.

我怎样才能得到一个简单的列表,表明A中的每个项目是否出现在B(1)或不是(0)中,如下所示:

1 0 0 0 0 0 1 0 1 1 0 1 1 1 0 1 1 0 0 0 

当我尝试回答第二个问题时,我遇到同样的问题:

test_non_match <- function(item_vector_A, item_vector_B){
ifelse(item_vector_B == item_vector_A, print("*match*"), print(item_vector_B))
}
lapply(A, B, FUN = test_non_match) -> results2
results2
[[1]]
[1] "1" "1" "1" "1" "#"  "$" "$" "1" "2" "2" "1" "d" "d" "*match*" "*match*" "*match*" "*match*" "1" "3" "2" "2" "F" "2" "2" "2" "5" "5" "5" "@" "5" "6" "5" "z" "z" "S" "S"      
[[2]]
[1] "1" "1" "1" "1" "#" "$" "$" "1" "2" "2" "1" "d" "d" "i" "i" "i" "i" "1" "3" "2" "2" "F" "2" "2" "2" "5" "5" "5" "@" "5" "6" "5" "z" "z" "S" "S"
[[3]]
[1] "1" "1" "1" "1" "#" "$" "$" "1" "2" "2" "1" "d" "d" "i" "i" "i" "i" "1" "3" "2" "2" "F" "2" "2" "2" "5" "5" "5" "@" "5" "6" "5" "z" "z" "S" "S"

它列出了整个矢量,而我希望有这样的东西:

[1] *match*
[1] *match*
[1] *match*
[1] *match*
[1] *match*
[1] *match*
[1] *match*
[1] *match*
[1] *match*
[1] *match*
[1] *match*
[1] d
[1] d
[1] *match*
[1] *match*
[1] *match*
[1] *match*
[1] *match*
[1] *match*
[1] *match*
[1] *match*
[1] F
[1] *match*
[1] *match*
[1] *match*
[1] *match*
[1] *match*
[1] *match*
[1] z
[1] z
[1] S
[1] S

我是否需要使用其他类型的apply()函数?

2 个答案:

答案 0 :(得分:2)

除了上面的替代方案,您可能需要查看%chin%,这是data.table包中%in%的更快版本:

ifelse (B %chin% A, "*match*", B)

答案 1 :(得分:1)

您可以使用%in%并测试A %in% B!(B %in% A )。要在您的问题中重现输出:

as.numeric(A %in% B)
 [1] 1 0 0 0 0 0 1 0 1 1 0 1 1 1 0 1 1 0 0 0

并按照Ferdinand.kraft的建议:

ifelse (B %in% A, "*match*", B)
 [1] "*match*" "*match*" "*match*" "*match*" "*match*" "*match*" "*match*" "*match*" "*match*" "*match*" "*match*" "d"       "d"       "*match*" "*match*" "*match*" "*match*" "*match*" "*match*"
[20] "*match*" "*match*" "F"       "*match*" "*match*" "*match*" "*match*" "*match*"  "*match*" "*match*" "*match*" "*match*" "*match*" "z"       "z"       "S"       "S"