match()与%运算符中的%

Ste*_*pré 6 r match

从我读到的 ?match()

"%in%"< - function(x,table)match(x,table,nomatch = 0)> 0

为什么我会使用不同的结果 match(x, dict[["word"]], 0L)

vapply(strsplit(df$text, " "), 
   function(x) sum(dict[["score"]][match(x, dict[["word"]], 0L)]), 1)
#[1]  2 -2  3 -2
Run Code Online (Sandbox Code Playgroud)

与使用时相比 dict[["word"]] %in% x

vapply(strsplit(df$text, " "), 
       function(x) sum(dict[["score"]][dict[["word"]] %in% x]), 1)
#[1]  2 -2  1 -1
Run Code Online (Sandbox Code Playgroud)

数据

library(dplyr)
df <- data_frame(text = c("I love pandas", "I hate monkeys", 
                          "pandas pandas pandas", "monkeys monkeys"))
dict <- data_frame(word = c("love", "hate", "pandas", "monkeys"),
                   score = c(1,-1,1,-1))
Run Code Online (Sandbox Code Playgroud)

更新

理查德的解释之后,我现在理解了我最初的误解.的%in%操作者返回一个逻辑向量:

> sapply(strsplit(df$text, " "), function(x) dict[["word"]] %in% x)
      [,1]  [,2]  [,3]  [,4]
[1,]  TRUE FALSE FALSE FALSE
[2,] FALSE  TRUE FALSE FALSE
[3,]  TRUE FALSE  TRUE FALSE
[4,] FALSE  TRUE FALSE  TRUE
Run Code Online (Sandbox Code Playgroud)

match()返回位置编号:

> sapply(strsplit(df$text, " "), function(x) match(x, dict[["word"]], 0L))
[[1]]
[1] 0 1 3

[[2]]
[1] 0 2 4

[[3]]
[1] 3 3 3

[[4]]
[1] 4 4
Run Code Online (Sandbox Code Playgroud)

Ric*_*ven 5

match() 返回第一个匹配的位置的整数向量,如果该位置不是第一个,则大于1.

%in%返回一个逻辑向量,其中匹配(TRUE)始终为 1(表示为整数时).

因此,计算中的总和可能会有所不同.