在带有 sapply 的函数中使用 str_split 和 union 的意外结果

Unexpected results using str_split and union in a function with sapply

鉴于此 data.frame:

library(dplyr)
library(stringr)
ml.mat2 <- structure(list(value = c("a", "b", "c"), ground_truth = c("label1, label3", 
"label2", "label1"), predicted = c("label1", "label2,label3", 
"label1")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-3L))

glimpse(ml.mat2)
Observations: 3
Variables: 3
$ value        <chr> "a", "b", "c"
$ ground_truth <chr> "label1, label3", "label2", "label1"
$ predicted    <chr> "label1", "label2,label3", "label1"

在根据 ,.

拆分重复标签后,我想测量每一行 ground_truthpredicted 之间的交叉长度

换句话说,我希望结果长度为 3,值为 2 2 1

我写了一个函数来执行此操作,但它似乎只能在 sapply 之外工作:

m_fn <- function(x,y) length(union(unlist(sapply(x, str_split,",")), 
                             unlist(sapply(y, str_split,","))))

m_fn(ml.mat2$ground_truth[1], y = ml.mat2$predicted[1])

[1] 2

m_fn(ml.mat2$ground_truth[2], y = ml.mat2$predicted[2])

[1] 2

m_fn(ml.mat2$ground_truth[3], y = ml.mat2$predicted[3])

[1] 1

而不是像这样手动或循环遍历数据集的行,我希望能够像这样用 sapply 向量化解决方案:

sapply(ml.mat2$ground_truth, m_fn, ml.mat2$predicted)

然而,意想不到的结果是:

label1, label3         label2         label1 
             4              3              3

由于您在相同的观察大小内进行交互,因此您可以生成行号的索引并 运行 它在您的 sapply:

sapply(1:nrow(ml.mat2), function(i) m_fn(x = ml.mat2$ground_truth[i], y = ml.mat2$predicted[i])) 

#[1] 2 2 1

seq_len:

sapply(seq_len(nrow(ml.mat2)), function(i) 
  m_fn(x = ml.mat2$ground_truth[i], y = ml.mat2$predicted[i]))