Learn R Programming

memisc (version 0.11-11)

recode: Recode factors and numeric vectors

Description

recode substitutes old values of a factor or a numeric vector by new ones, just like the recode facilities in some commercial statistical packages.

Usage

## S3 method for class 'default':
recode(x,...,otherwise="NA",to.factor=FALSE)
  ## S3 method for class 'factor':
recode(x,...,otherwise="NA")

Arguments

x
A factor or numerical vector
...
One or more assignment expressions, the value side specifies the codes to change, the target side gives the new code. Vectors may appear on the value side. If the x is numeric a call to range may also appear. In t
otherwise
a character string or some other value that the result may obtain. If equal to NA or "NA", original codes not given an explicit new code are recoded into NA. If equal to "copy", original
to.factor
a logical value; if TRUE, a numeric argument is recoded into a factor, if TRUE, the result is numeric if x is numeric. Defaults to TRUE if new codes are character strings and defaults to

Value

  • The object x with new codes specified by the ... arguments.

Examples

Run this code
df <- data.frame(a = 1:7,
                   f = factor(letters[1:7]))

transform(df,
  r = recode(a,   1  -> 5,
                  2:3-> 2,
                  7  -> 6))
  
transform(df,
  r = recode(a,   1  -> 5,
                  2:3-> 2,
                  7  -> 6,
                  otherwise="copy"))

transform(df,
  r = recode(a,   1  -> 5,
                  2:3-> 2,
                  7  -> 6,
                  otherwise=100))

transform(df,
  r = recode(a,   1   -> 5,
                  2:3 -> 2,
                  7   -> 6,
                  to.factor=TRUE))

transform(df,
  r = recode(a,   1   -> "a",
                  2:3 -> "b",
                  7   -> "c"))

transform(df,
  r = recode(a,   1   -> "a",
                  2:3 -> "b",
                  7   -> "c",
                  otherwise="z"))

transform(df,
  r = recode(a,   1   -> "a",
                  2:3 -> "b",
                  7   -> "c",
                  otherwise="copy"))

transform(df,
  r = recode(a,   range(min,3) -> "a",
                             5 -> "b",
                             7 -> "d",
                  otherwise="copy"))

transform(df,
  r = recode(a,   range(max,3) -> "a",
                             1 -> "b",
                             2 -> "d",
                  otherwise="copy"))

transform(df,
  r = recode(f, letters[1:3] -> "a",
                letters[4:5] -> "b",
                "f"          -> "c"))

transform(df,
  r = recode(f, letters[1:3] -> "a",
                letters[4:5] -> "b",
                "f"          -> "c",
                otherwise="copy"))

transform(df,
  r = recode(f, letters[1:3] -> "a",
                letters[4:5] -> "b",
                "f"          -> "c",
                otherwise="z"))

Run the code above in your browser using DataLab