![](/img/trans.png)
[英]How to write an index/match function for dates and times that finds/returns the first value that is greater or less than the search value?
[英]Equivalent of index - match in Excel to return greater than the lookup value
在RI中,需要執行與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
在每個國家(數據集A)的2009年GNI上,我想找出哪個GNI2004剛好大於或等於GNI2009,然后返回該行(數據集)的相應銷售值(s1,s2 ...) B)。 我想對表A中2009年的每一個國家/地區gni行重復此操作。
例如:數據集A中的GNI2009 of 2698
Nigeria
將返回:
GNI2004 s1 s2 s3 s4
2976 89 10 15 1
在Excel中,我想這將類似於Index and Match,其中匹配條件為match(look up value, look uparray,-1)
您可以嘗試data.table
的滾動data.table
,該滾動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
。
有關更多信息,請參見此處 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.