Learn R Programming

car (version 3.0-6)

recode: Recode a Variable

Description

Recodes a numeric vector, character vector, or factor according to simple recode specifications. Recode is an alias for recode that avoids name clashes with packages, such as Hmisc, that have a recode function.

Usage

recode(var, recodes, as.factor, as.numeric=TRUE, levels)

Recode(...)

Arguments

var

numeric vector, character vector, or factor.

recodes

character string of recode specifications: see below.

as.factor

return a factor; default is TRUE if var is a factor, FALSE otherwise.

as.numeric

if TRUE (the default), and as.factor is FALSE, then the result will be coerced to numeric if all values in the result are numerals---i.e., represent numbers.

levels

an optional argument specifying the order of the levels in the returned factor; the default is to use the sort order of the level names.

...

arguments to be passed to recode.

Value

a recoded vector of the same length as var.

Details

Recode specifications appear in a character string, separated by semicolons (see the examples below), of the form input=output. If an input value satisfies more than one specification, then the first (from left to right) applies. If no specification is satisfied, then the input value is carried over to the result. NA is allowed on input and output. Several recode specifications are supported:

single value

For example, 0=NA.

vector of values

For example, c(7,8,9)='high'.

range of values

For example, 7:9='C'. The special values lo and hi may appear in a range. For example, lo:10=1. Note: : is not the R sequence operator. In addition you may not use : with the collect operator, so for example c(1, 3, 5:7) will cause an error.

else

everything that does not fit a previous specification. For example, else=NA. Note that else matches all otherwise unspecified values on input, including NA.

If all of the output values are numeric, and if as.factor is FALSE, then a numeric result is returned; if var is a factor, then by default so is the result.

References

Fox, J. and Weisberg, S. (2019) An R Companion to Applied Regression, Third Edition, Sage.

See Also

cut, factor

Examples

Run this code
# NOT RUN {
x<-rep(1:3,3)
x
## [1] 1 2 3 1 2 3 1 2 3
recode(x, "c(1,2)='A'; 
	else='B'")
## [1] "A" "A" "B" "A" "A" "B" "A" "A" "B"
Recode(x, "1:2='A'; 3='B'")
## [1] "A" "A" "B" "A" "A" "B" "A" "A" "B"
# }

Run the code above in your browser using DataLab