Search, match, and look up values (like Excel's functions INDEX + MATCH).
In Excel, we can use VLOOKUP, HLOOKUP, XLOOKUP (a new function released in 2019),
or the combination of INDEX and MATCH to search, match, and look up values.
Here I provide a similar function.
LOOKUP(
data,
vars,
data.ref,
vars.ref,
vars.lookup,
return = c("new.data", "new.var", "new.value")
)data |
Main data. |
vars |
Character (vector), specifying the variable(s) to be searched in |
data.ref |
Reference data containing both the reference variable(s) and the lookup variable(s). |
vars.ref |
Character (vector), with the same length and order as |
vars.lookup |
Character (vector), specifying the variable(s) to be looked up and returned from |
return |
What to return. Default ( |
If multiple values were simultaneously matched, a warning message would be printed.
New data object, new variable, or new value (see the parameter return).
dplyr::left_join
ref=data.table(City=rep(c("A", "B", "C"), each=5),
Year=rep(2013:2017, times=3),
GDP=RANDBETWEEN(1000:2000, n=15, seed=1),
PM2.5=RANDBETWEEN(10:300, n=15, seed=1))
ref
data=data.table(sub=1:5,
city=c("A", "A", "B", "C", "C"),
year=c(2013, 2014, 2015, 2016, 2017))
data
LOOKUP(data, c("city", "year"), ref, c("City", "Year"), "GDP")
LOOKUP(data, c("city", "year"), ref, c("City", "Year"), c("GDP", "PM2.5"))Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.