Function to flexibly recode values of a variable. Can match values and replace with new codes, assign codes based on intervals for a continuous variable, or code a linear trend given a start and end point.

recode(x, values, codes = NULL, default = 0, type = NULL)

Arguments

x

A vector.

values

Either a vector of values to replace, or a list of vectors for the sets of values to replace. Values of the form '(x,y)' or '[x,y]' result in assignment based on an interval from x to y, while values of the form 'x,y' result in a linear trend ranging from 0 to 1 over the range x to y.

codes

A vector of values, either a single value or a vector matching in length with to_replace.

default

The default value to return as output for all cases that are not recoded.

type

A character string, either 'replace', 'linear', or 'interval'. If not provided function attempts to determine from input to values.

Value

A vector.

Examples

# Assigning by matching categories
x <- rep( LETTERS[1:3], each = 3 )
recode( x, list( 'A', c('B', 'C') ) )
#> [1] 1 1 1 2 2 2 2 2 2
recode( x, c( 'A', 'B', 'C' ), c( -1, 0, 1 ) )
#> [1] -1 -1 -1  0  0  0  1  1  1

# Assigning by intervals
x <- seq( -1.5, 1.5, .5 )
cbind(x, recode( x, c( '(-Inf,0]', '(0,Inf]' ) ) )
#>         x  
#> [1,] -1.5 1
#> [2,] -1.0 1
#> [3,] -0.5 1
#> [4,]  0.0 1
#> [5,]  0.5 2
#> [6,]  1.0 2
#> [7,]  1.5 2

# Linear trend
cbind(x, recode( x, '-1,1' ) )
#>         x     
#> [1,] -1.5 0.00
#> [2,] -1.0 0.00
#> [3,] -0.5 0.25
#> [4,]  0.0 0.50
#> [5,]  0.5 0.75
#> [6,]  1.0 1.00
#> [7,]  1.5 1.00