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)
old, new | Vectors of equal length giving old and new codes. |
---|
A "spliced" list with names from old
and values from new
. The
kind of data structure that you can feed to ...
in dplyr::recode()`.
Thanks to David Kenfack for inspiring this function.
Other general functions to edit data in place: fill_na
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"#> # 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#> # A tibble: 8 x 1 #> sp #> <chr> #> 1 spp3 #> 2 spp2 #> 3 spp3 #> 4 spp4 #> 5 spp3 #> 6 spp4 #> 7 spp3 #> 8 spp3