A simple interface to recoding a vector based on the coding linking mechanism. If the vector has the "rcoder.coding" attribute, then the coding object stored in that attribute will be used by default.

recode_vec(vec, to, from = NULL, .embed = TRUE, .bpr = TRUE)

Arguments

vec

A vector

to

A coding object to which the vector will be recoded

from

A coding object that describes the current coding of the vector. Defaults to the "rcoder.coding" attribute value, if it exists, _or_ the "bpr.coding" value (from blueprintr). If neither are found, `from` stays `NULL` and the function errors.

.embed

If `TRUE`, `from` will be stored in the "rcoder.coding" attribute

.bpr

If `TRUE`, adds the _character_ representation of the coding to the "bpr.coding" attribute. Used for interop with blueprintr variable decorations

Value

The recoded vector

See also

[assign_coding()]

Examples

# Using an explicit `from`
vec <- sample(1:3, 50, replace = TRUE)
cdng_old <- coding(code("Yes", 3), code("Maybe", 2), code("No", 1))
cdng_new <- coding(code("Yes", 2), code("Maybe", 1), code("No", 0))
recode_vec(vec, to = cdng_new, from = cdng_old)
#>  [1] 2 2 0 1 0 0 2 0 0 2 0 0 1 0 0 0 1 1 2 1 2 0 0 2 2 2 0 1 1 0 1 0 2 2 2 1 2 0
#> [39] 1 1 1 1 1 2 0 2 1 0 0 0
#> attr(,"rcoder.coding")
#> <Coding>
#> # A tibble: 3 × 5
#>   link  label value description missing
#>   <chr> <chr> <dbl> <chr>       <lgl>  
#> 1 Yes   Yes       2 Yes         FALSE  
#> 2 Maybe Maybe     1 Maybe       FALSE  
#> 3 No    No        0 No          FALSE  
#> attr(,"bpr.coding")
#> [1] "coding(code(\"Yes\", 2), code(\"Maybe\", 1), code(\"No\", 0))"

# Using an implicit `from` with assign_coding()
vec <- sample(1:3, 50, replace = TRUE)
vec <- assign_coding(vec, cdng_old)
recode_vec(vec, cdng_new)
#>  [1] 1 2 2 2 0 1 0 2 0 0 1 2 2 0 0 1 0 1 1 1 2 2 0 2 2 0 2 1 1 0 1 0 2 1 1 1 1 1
#> [39] 0 1 1 0 0 2 1 1 0 0 0 2
#> attr(,"rcoder.coding")
#> <Coding>
#> # A tibble: 3 × 5
#>   link  label value description missing
#>   <chr> <chr> <dbl> <chr>       <lgl>  
#> 1 Yes   Yes       2 Yes         FALSE  
#> 2 Maybe Maybe     1 Maybe       FALSE  
#> 3 No    No        0 No          FALSE  
#> attr(,"bpr.coding")
#> [1] "coding(code(\"Yes\", 2), code(\"Maybe\", 1), code(\"No\", 0))"