recodes recodes the values of one or more variables in a data frame

recodes(data, vars, from, to)

Arguments

data

a data frame.

vars

character vector of variable names.

from

a vector of values or conditions (see Details).

to

a vector of replacement values.

Value

a data frame

Details

  • For each variable in the vars parameter, values are checked against the list of values in the from vector. If a value matches, it is replaced with the corresponding entry in the to vector.

  • Once a given observation's value matches a from value, it is recoded. That particular observation will not be recoded again by that recodes() statement (i.e., no chaining).

  • One or more values in the from vector can be an expression, using the dollar sign ($) to represent the variable being recoded. If the expression evaluates to TRUE, the corresponding to value is returned.

  • If the number of values in the to vector is less than the from vector, the values are recycled. This lets you convert several values to a single outcome value (e.g., NA).

  • If the to values are numeric, the resulting recoded variable will be numeric. If the variable being recoded is a factor and the to values are character values, the resulting variable will remain a factor. If the variable being recoded is a character variable and the to values are character values, the resulting variable will remain a character variable.

Note

See the vignette for detailed examples.

Examples

df <- data.frame(x = c(1, 5, 7, 3, 0),
                 y = c(9, 0, 5, 9, 2),
                 z = c(1, 1, 2, 2, 1)
                 )
df <- recodes(df, 
              vars = c("x", "y"), 
              from = 0, to = NA)
df <- recodes(df, 
              vars = "z", 
              from = c(1, 2), to = c("pass", "fail"))