recode: Recode a Variable

View source: R/S03_Utilities.R

recodeR Documentation

Recode a Variable

Description

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.

Usage

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') ) )
recode( x, c( 'A', 'B', 'C' ), c( -1, 0, 1 ) )

# Assigning by intervals
x <- seq( -1.5, 1.5, .5 )
cbind(x, recode( x, c( '(-Inf,0]', '(0,Inf]' ) ) )

# Linear trend
cbind(x, recode( x, '-1,1' ) )


rettopnivek/arfpam documentation built on Oct. 20, 2024, 7:24 p.m.