recode

0th

Percentile

Recode a Variable

Recodes a numeric vector, character vector, or factor according to simple recode specifications.

Keywords
manip
Usage
recode(var, recodes, as.factor.result, as.numeric.result=TRUE, levels)
Arguments
var
numeric vector, character vector, or factor.
recodes
character string of recode specifications: see below.
as.factor.result
return a factor; default is TRUE if var is a factor, FALSE otherwise.
as.numeric.result
if TRUE (the default), and as.factor.result 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.
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: [object Object],[object Object],[object Object],[object Object] If all of the output values are numeric, and if as.factor.result is FALSE, then a numeric result is returned; if var is a factor, then by default so is the result.

Value

  • a recoded vector of the same length as var.

References

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

See Also

cut, factor

Aliases
  • recode
Examples
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"
Documentation reproduced from package car, version 2.0-11, License: GPL (>= 2)

Community examples

ryantcragun@gmail.com at May 7, 2019 car v3.0-2

# By including just a single value, it's possible to recode just that value and leave all other values unchanged: NEWVAR <- recode(OLDVAR, '99=NA') # This would copy all the other values but recode 99 as NA.