LOOKUP: Search, match, and look up values (like Excel's functions...

Description Usage Arguments Details Value See Also Examples

View source: R/bruceR_basic.R

Description

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.

Usage

1
2
3
4
5
6
7
8
LOOKUP(
  data,
  vars,
  data.ref,
  vars.ref,
  vars.lookup,
  return = c("new.data", "new.var", "new.value")
)

Arguments

data

Main data.

vars

Character (vector), specifying the variable(s) to be searched in data.

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, specifying the reference variable(s) to be matched in data.ref.

vars.lookup

Character (vector), specifying the variable(s) to be looked up and returned from data.ref.

return

What to return. Default ("new.data") is to return a data frame with the lookup values added. You may also set it to "new.var" or "new.value".

Details

If multiple values were simultaneously matched, a warning message would be printed.

Value

New data object, new variable, or new value (see the parameter return).

See Also

dplyr::left_join()

XLOOKUP: Excel University

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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"))

bruceR documentation built on June 22, 2021, 1:06 a.m.