Skip to contents

Lookup by Matching Values in Multiple Columns

Usage

multiColumnLookup(data, lookup, value = NULL, drop = TRUE, includeKeys = FALSE)

Arguments

data

data frame for which to lookup values in the lookup table

lookup

lookup table defining the key values to be matched against the values in the corresponding columns in data and the corresponding lookup values that are to be returned

value

name of column(s) in lookup containing the value(s) to be looked up. Default: name of the last column in lookup

drop

logical indicating whether or not to return a vector instead of a one-column data frame in case that there is only one value column. The default is TRUE

includeKeys

logical indicating whether or not to include the key column(s) in the returned data frame (for more than one value column or drop = FALSE). The default is FALSE

Value

If value is of length one and drop = TRUE) a vector with as many elements as there are rows in data is returned. Otherwise a data frame with as many rows as there are rows in data

and with the columns named in value is returned.

Examples

(persons <- rbind(
  noFactorDataFrame(name = "Peter", city = "Berlin"),
  noFactorDataFrame(name = "Paul", city = "Paris"),
  noFactorDataFrame(name = "Mary", city = "Berlin"),
  noFactorDataFrame(name = "Paul", city = "Berlin"),
  noFactorDataFrame(name = "Peter", city = "Paris")
))
#>    name   city
#> 1 Peter Berlin
#> 2  Paul  Paris
#> 3  Mary Berlin
#> 4  Paul Berlin
#> 5 Peter  Paris

# Who is cool, which city is cool and which combination is coolest?
(is_cool <- kwb.utils::safeRowBindAll(list(
  noFactorDataFrame(name = "Paul", city = "Berlin", value = "astro-cool"),
  noFactorDataFrame(city = "Berlin", value = "cool"),
  noFactorDataFrame(name = "Paul", value = "mega-cool"),
  noFactorDataFrame(city = "Paris", value = "ca va")
)))
#>   name   city      value
#> 1 Paul Berlin astro-cool
#> 2 <NA> Berlin       cool
#> 3 Paul   <NA>  mega-cool
#> 4 <NA>  Paris      ca va

# Lookup the coolness based on name and city
coolness <- multiColumnLookup(persons, is_cool, value = "value")

# Add the coolness column
cbind(persons, coolness)
#>    name   city   coolness
#> 1 Peter Berlin       cool
#> 2  Paul  Paris  mega-cool
#> 3  Mary Berlin       cool
#> 4  Paul Berlin astro-cool
#> 5 Peter  Paris      ca va