r-相当于Excel中的索引匹配,以返回大于查找值的值



在R中,我需要执行与Excel中的索引匹配类似的函数,该函数返回的值略大于查找值。

数据集A

Country     GNI2009           
Ukraine     6604
Egypt       5937
Morocco     5307
Philippines 4707
Indonesia   4148
India       3677
Viet Nam    3180
Pakistan    2760
Nigeria     2699

数据集B

GNI2004 s1  s2  s3  s4
6649    295 33  59  3
6021    260 30  50  3
5418    226 27  42  2
4846    193 23  35  2
4311    162 20  29  2
3813    134 16  23  1
3356    109 13  19  1
2976    89  10  15  1
2578    68  7   11  0
2248    51  5   8   0
2199    48  5   8   0

在2009年水平上,每个国家的国民总收入(数据集A),我想找出哪一个国民总收入2004刚好大于或等于2009年国民总收入,然后返回该行的相应销售值(s1,s2…)(数据集B)。我想对表A中2009年每个国家的gni行重复这一点。

例如:数据集a中具有GNI2009 of 2698Nigeria将返回:

GNI2004 s1  s2  s3  s4
2976    89  10  15  1

在Excel中,我想这将类似于Index and Match,其中匹配条件为match(look up value, look uparray,-1)

您可以尝试data.table的滚动连接,该连接旨在实现

library(data.table) # V1.9.6+
indx <- setDT(DataB)[setDT(DataA), roll = -Inf, on = c(GNI2004 = "GNI2009"), which = TRUE]
DataA[, names(DataB) := DataB[indx]]
DataA  
#        Country GNI2009 GNI2004  s1 s2 s3 s4
# 1:     Ukraine    6604    6649 295 33 59  3
# 2:       Egypt    5937    6021 260 30 50  3
# 3:     Morocco    5307    5418 226 27 42  2
# 4: Philippines    4707    4846 193 23 35  2
# 5:   Indonesia    4148    4311 162 20 29  2
# 6:       India    3677    3813 134 16 23  1
# 7:    Viet Nam    3180    3356 109 13 19  1
# 8:    Pakistan    2760    2976  89 10 15  1
# 9:     Nigeria    2699    2976  89 10 15  1

这里的想法是,对于GNI2009中的每一行,在GNI2004中找到最接近的相等/更大的值,得到行索引和子集。然后我们用结果更新DataA


请参阅此处了解更多信息。

最新更新