LOOKUP | R Documentation |
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 argument return
).
dplyr::left_join()
ref = data.table(City=rep(c("A", "B", "C"), each=5),
Year=rep(2013:2017, times=3),
GDP=sample(1000:2000, 15),
PM2.5=sample(10:300, 15))
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"))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.