等效索引 - 在 Excel 到 return 中匹配大于查找值
Equivalent of index - match in Excel to return greater than the lookup value
在 R 中,我需要在 Excel 中执行与索引匹配类似的功能,其中 return 的值刚好大于查找值。
数据集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
在每个国家(数据集 A)的 2009 年 GNI 水平上,我想找出哪个 GNI2004 刚好大于或等于 GNI2009,然后 return 相应的销售额值(s1,s2。 ..) 在该行(数据集 B)。我想对 table A 中 2009 年的每一行 Country-gni 重复此操作。
例如:Nigeria
与数据集 A 中的 GNI2009 of 2698
将 return:
GNI2004 s1 s2 s3 s4
2976 89 10 15 1
在 Excel 中,我想这会类似于 Index 和 Match,其中匹配条件为 match(look up value, look uparray,-1)
您可以尝试 data.table
s 滚动连接,它旨在实现
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
中找到最接近的 equal/bigger 值,获取行索引和子集。然后我们用结果更新DataA
。
有关详细信息,请参阅 here。
在 R 中,我需要在 Excel 中执行与索引匹配类似的功能,其中 return 的值刚好大于查找值。
数据集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
在每个国家(数据集 A)的 2009 年 GNI 水平上,我想找出哪个 GNI2004 刚好大于或等于 GNI2009,然后 return 相应的销售额值(s1,s2。 ..) 在该行(数据集 B)。我想对 table A 中 2009 年的每一行 Country-gni 重复此操作。
例如:Nigeria
与数据集 A 中的 GNI2009 of 2698
将 return:
GNI2004 s1 s2 s3 s4
2976 89 10 15 1
在 Excel 中,我想这会类似于 Index 和 Match,其中匹配条件为 match(look up value, look uparray,-1)
您可以尝试 data.table
s 滚动连接,它旨在实现
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
中找到最接近的 equal/bigger 值,获取行索引和子集。然后我们用结果更新DataA
。
有关详细信息,请参阅 here。