r - 在数据框中查找与 R 中最接近的匹配行

标签 r

我在 R 中有一个数据框,其中包含 5 行(记录),每行 3 个属性。现在,给定具有相同 20 个属性的新记录,就其内容(值)而言,找到 10 行中哪一行与该新行最相似的最佳方法是什么?

现有数据

Age Occupation Nationality,
23  Builder    German,
29  Worker     British,
45  Contractor Vietnamese,
24  Engineer   German,
28  Doctor     Indian,

新数据

23  Doctor German

预期输出

23  Builder    German

我想返回第 1 行,即上面的行,因为两个属性匹配

最佳答案

您可以将 stringdist 中的 stringdistmethod=jaccard 一起使用。通过使用 Map,我们将 df 的列与列表 newdata 的相应元素进行比较。即 df 中的 Age 列用于将 stringdist23 进行比较,OccupationDoctor 等等...应用 stringdist 函数后,我们为每个列表获取长度等于 nrow(df) 的数值元素。使用 Reduce 添加相应的值 (+),然后我们使用 which.min< 查找 最小值 (输出将是逻辑索引)。该索引用于对 df 进行子集化。

library(stringdist)
df[which.min(Reduce(`+`,Map(stringdist,df, newdata,
                                 method='jaccard'))),]

#  Age Occupation Nationality
#1  23    Builder      German

数据

df <-  structure(list(Age = c(23, 29, 45, 24, 28), Occupation = c("Builder", 
"Worker", "Contractor", "Engineer", "Doctor"), Nationality = c("German", 
"British", "Vietnamese", "German", "Indian")), .Names = c("Age", 
"Occupation", "Nationality"), row.names = c(NA, -5L), class = "data.frame")

newdata <- list(23,"Doctor","German")

关于r - 在数据框中查找与 R 中最接近的匹配行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27128380/

相关文章:

r - install_bitbucket 失败并出现 404 错误

r - 开关有逻辑参数的问题

r - 多个矩阵的打印方法

使用 plm() 和 vcovHC() 进行 Hausman-Taylor 估计器的稳健标准误差估计

r - 使用 sf 对象的自定义几何图形扩展 ggplot2

r - 在同一个 dplyr 链中使用 summarise 和 summarise_at

r - geom_bar的宽度和间隙(ggplot2)

r - 更改默认提示和R中的输出行前缀?

Python 相当于 R 中的 select.list

r - R data.table 是否记录为通过引用作为参数传递?