r - 获取两个R数据表中每个元素最接近的数量

标签 r data.table

<分区>

假设我有 2 个包含任意位置和分数的数据表。每个数据表中的所有位置都是唯一的。例如:

dt1:

position score
10       6.2
21       4.5
37       3.6

dt2:

position score
8        12.2
32       4.2
45       3.8
52       4.9

我想在 df2 中找到最接近 df1 中每一行的位置。因此,例如,df1 中的位置 10 将位置 8 的 df2 作为最接近的。最后的结果会是这样的:

position.dt1 score.dt1 position.dt2 score.dt2 distance
10           6.2       8            12.2      2
21           4.5       32           4.2       11
37           3.6       32           4.2       5

如何在 R 中实现这一点?

最佳答案

在基础 R 中

inds = sapply(dt1$position, function(x) which.min(abs(x - dt2$position)))
transform(dt1, pos.dt2 = dt2$position[inds],
          score.dt2 = dt2$score[inds],
          distance = abs(position - dt2$position[inds]))
#  position score pos.dt2 score.dt2 distance
#1       10   6.2       8      12.2        2
#2       21   4.5      32       4.2       11
#3       37   3.6      32       4.2        5

关于r - 获取两个R数据表中每个元素最接近的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58070507/

相关文章:

r - 使用 dplyr 过滤 SQLite 数据库时,是否应该避免 `|`?

r - 如何在R中的数据框中的列中查找和删除具有相同连续值的一定数量的行?

r - 如何创建一个带有字符串和每个重复对应数字的向量

r - data.table 的 CJ 是否应该继续容纳具有重复元素的参数?

r - 使用 data.table 中的函数更新变量?

r - 动态侧边栏菜单 R Shiny

r - ggplot - facet wrap - 调整比例以显示值之间的明显差异

r - 如何在两个 data.tables(或 data.frames)的行之间创建随机匹配

R data.table 1.9.2 关于 setkey 的问题

r - 如何矢量化依赖于 R 中先前计算的函数?