gpt4 book ai didi

r - R中合并期间的数值比较

转载 作者:行者123 更新时间:2023-12-01 08:58:27 25 4
gpt4 key购买 nike

数据帧d1:

x  y
4 10
6 20
7 30

数据帧d2:

x   z
3 100
6 200
9 300

如何通过 "x" 合并 d1d2,其中 d1$x 应匹配d2$x 中的完全匹配或下一个更高的数字。输出应如下所示:

x   y    z
4 10 200 # (4 is matched against next higher value that is 6)
6 20 200 # (6 is matched against 6)
7 30 300 # (7 is matched against next higher value that is 9)

如果 merge() 不能做到这一点,那么还有其他方法可以做到这一点吗? for 循环非常慢。

最佳答案

使用 滚动连接data.table 非常简单:

require(data.table)   ## >= 1.9.2
setkey(setDT(d1), x) ## convert to data.table, set key for the column to join on
setkey(setDT(d2), x) ## same as above

d2[d1, roll=-Inf]

# x z y
# 1: 4 200 10
# 2: 6 200 20
# 3: 7 300 30

关于r - R中合并期间的数值比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24099498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com