首页 > 解决方案 > 在 R 中使用 stringdist_join() 进行模糊连接,错误:下标分配中不允许使用 NA

问题描述

首先,如果我的格式不好,我很抱歉,这是我第一次发帖,(也是编程和 R 的新手)

我正在尝试将两个数据框合并到字符串变量上。我正在合并可能不完全匹配的大学名称,所以我希望使用模糊或近似字符串匹配函数进行合并。当我找到“fuzzyjoin”包时,我很高兴。

来自 cranR:stringdist_join:根据列的模糊字符串匹配连接两个表

stringdist_join(x, y, by = NULL, max_dist = 2, method = c("osa", "lv",
  "dl", "hamming", "lcs", "qgram", "cosine", "jaccard", "jw","soundex"), mode = "inner", ignore_case = FALSE, distance_col = NULL, ...)

我的代码:

stringdist_left_join(new, institutions, by = c("tm_9_undergradu" = "Institution.Name"))

错误:

Error in dists[include] <- stringdist::stringdist(v1[include], v2[include],  : 
NAs are not allowed in subscripted assignments

我知道这些列中有一些 NA,但我不确定如何删除它们,因为我也需要它们。我知道 NA 的其他加入和合并功能将被忽略。有谁知道解决此包的此错误或以另一种方式对字符串进行近似连接的方法。谢谢您的帮助。

标签: rdplyrmergefuzzy-comparisonfuzzyjoin

解决方案


这个答案对我有用,来自GitHub

第 1 步:找出哪个 Df 具有NAs

`which(is.na(df1))
 which(is.na(df2))`

第2步:NAs用其他东西替换。 df1[is.na(df1)] <- "empty_string"

第 3 步:运行连接(出现错误时我正在使用的代码)

`test1 <- msa_table %>%
   as_tibble() %>% 
   unlist() %>%
   mutate(msa = sub("\\(.*)","", as.character(msa)) %>% 
   stringdist_full_join(msa_table, df1, by = 'msa', max_dist = 2)` 

结果对我来说没有相同的错误,但仍然NAs在我的表中。

希望这可以帮助!另外,要明确一点:这个解决方案来自 GitHub 上的 Anton Prokopyev '@prokopyev'。


推荐阅读