在 R 中使用 stringdist 和 data.table 时出现回收错误

Recycling error while using stringdist and data.table in R

我正在尝试对包含作者姓名的 data.table 基于 "first" 姓名的字典执行近似字符串匹配。我还设置了一个高于 0.9 的高阈值以提高匹配质量。

但是,我收到如下错误消息:

Warning message:
In [`<-.data.table`(x, j = name, value = value) :
Supplied 6 items to be assigned to 17789 items of column 'Gender_Dict' (recycled leaving remainder of 5 items).

即使我使用 signif(similarity_score,4).

将相似性匹配向下舍入到 4 位数字,也会出现此错误

关于输入数据和方法的更多信息:

  1. author_corrected_df 是一个 data.table,包含列:"Author" 和 "Author_Corrected"。 Author_Corrected 是相应作者的字母表示(例如:如果 Author = Jack123,则 Author_Corrected = Jack)。
  2. Author_Corrected 列可以包含正确名字的变体,例如:Jackk 而不是 Jack,我想在这个名为 Gender_Dict 的 author_corrected_df 中填充相应的性别。
  3. 另一个名为 first_names_dict 的 data.table 包含 'name'(即名字)和性别(0 代表女性,1 代表男性,2 代表领带)。
  4. 我想从每行 "Author_Corrected" 中找到与 first_names_dict 中的 'name' 最相关的匹配项,并填充相应的性别(0,1 之一,2).
  5. 为了使字符串匹配更严格,我使用了0.9720的阈值,否则在后面的代码中(下面未显示),未匹配的值将表示为NA。
  6. first_names_dict 和 author_corrected_df 可以从下面的 link 访问: https://wetransfer.com/downloads/6efe42597519495fcd2c52264c40940a20190612130618/0cc87541a9605df0fcc15297c4b18b7d20190612130619/6498a7
for (ijk in 1:nrow(author_corrected_df)){
  max_sim1 <- max(stringsim(author_corrected_df$Author_Corrected[ijk], first_names_dict$name, method = "jw", p = 0.1, nthread = getOption("sd_num_thread")), na.rm = TRUE)
  if (signif(max_sim1,4) >= 0.9720){
    row_idx1 <- which.max(stringsim(author_corrected_df$Author_Corrected[ijk], first_names_dict$name, method = "jw", p = 0.1, nthread = getOption("sd_num_thread")))
    author_corrected_df$Gender_Dict[ijk] <- first_names_dict$gender[row_idx1]
  } else {
    next
  }
}

执行时出现以下错误消息:

Warning message:
In `[<-.data.table`(x, j = name, value = value) :
  Supplied 6 items to be assigned to 17789 items of column 'Gender_Dict' (recycled leaving remainder of 5 items).

在了解错误所在以及是否有更快的方法来执行此类匹配方面(尽管后者是第二优先级),我们将不胜感激。

提前致谢。

根据之前的评论,我在这里 select 你的 selection 中最常见的性别:

for (ijk in 1:nrow(author_corrected_df)){
        max_sim1 <- max(stringsim(author_corrected_df$Author_Corrected[ijk], first_names_dict$name, method = "jw", p = 0.1, nthread = getOption("sd_num_thread")), na.rm = TRUE)
        if (signif(max_sim1,4) >= 0.9720){
                row_idx1 <- which.max(stringsim(author_corrected_df$Author_Corrected[ijk], first_names_dict$name, method = "jw", p = 0.1, nthread = getOption("sd_num_thread")))

                # Analysis of factor gender
                gender <- as.character( first_names_dict$gender[row_idx1] )

                # I take the (first) gender most present in selection 
                df_count <- as.data.frame( table(gender) )
                ref <- as.character ( df_count$test[which.max(df_count$Freq)] )
                value <- unique ( test[which(test == ref)] )

                # Affecting single character value to data frame
                author_corrected_df$Gender_Dict[ijk] <- value
        }
}

希望这对您有所帮助:)