Use this function inside dplyr::recode() to recode a vector based on values from two other vectors, where old and new codes are looked up. These lookup vectors are commonly stored in a dataframe and come from a .csv or spreadsheet file.

lookup(old, new)

Arguments

old, new

Vectors of equal length giving old and new codes.

Value

A "spliced" list with names from old and values from new. The kind of data structure that you can feed to ... in dplyr::recode()`.

Acknowledgment

Thanks to David Kenfack for inspiring this function.

See also

dplyr::recode()

Other general functions to edit data in place: fill_na

Examples

library(dplyr, warn.conflicts = FALSE) look <- tibble::tibble( old = c("spp1", "unknown"), new = c("spp3", "spp4") ) sp <- c("spp1", "spp2", "spp3", "unknown", "spp3", "unknown", "spp1", "spp1") recode(sp, lookup(look$old, look$new))
#> [1] "spp3" "spp2" "spp3" "spp4" "spp3" "spp4" "spp3" "spp3"
census <- tibble::tibble(sp = sp) mutate(census, new_sp = recode(sp, lookup(look$old, look$new)))
#> # A tibble: 8 x 2 #> sp new_sp #> <chr> <chr> #> 1 spp1 spp3 #> 2 spp2 spp2 #> 3 spp3 spp3 #> 4 unknown spp4 #> 5 spp3 spp3 #> 6 unknown spp4 #> 7 spp1 spp3 #> 8 spp1 spp3
# Overwrite mutate(census, sp = recode(sp, lookup(look$old, look$new)))
#> # A tibble: 8 x 1 #> sp #> <chr> #> 1 spp3 #> 2 spp2 #> 3 spp3 #> 4 spp4 #> 5 spp3 #> 6 spp4 #> 7 spp3 #> 8 spp3