car (version 1.0-15)

recode: Recode a Variable

Description

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

Usage

recode(var, recodes, as.factor.result)

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.

Value

  • a recoded vector of the same length as var; if var is a factor, then so is the result.

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.

See Also

cut, factor

Examples

Run this code
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 DataCamp Workspace