recode | R Documentation |
Transform the input vector into a new vector by replacing old values with new values according to the specified rules.
recode(x, fromto, ...)
## Default S3 method:
recode(x, fromto, ...)
## S3 method for class 'data.frame'
recode(x, fromto, ...)
## S3 method for class 'matrix'
recode(x, fromto, ...)
x |
atomic vector, variable to be recoded |
fromto |
two-column matrix or data frame, or a list |
... |
Only used in the default method and expects further elements of the recoding rule set |
This is a generic function that dispatches methods based on the class
of the fromto
argument, which expects the recoding rule(s).
If fromto
is a vector it should have an even number of elements. It is
interpreted such that values x = fromto[i]
is recoded into a value
fromto[i+1]
, x = fromto[i+2]
into fromto[i+3]
and so on.
If fromto
is a data frame, then it is expected to have two columns.
The mode of the result is determined by the mode of the second column of
fromto
. For each 'i', values of x
equal to fromto[i,1]
are replaced with fromto[i,2]
.
If fromto
is a matrix, it is converted to a data frame and an
appropriate method is used.
Vector of the same mode as second column of fromto
and length
as x
with the values recoded.
match
# Input vector
x <- c(1,2,3,4,3,2,1)
# Recoding with rules as a matrix
rmat <- matrix( c(1, 10, 4, 40), 2, 2, byrow=TRUE)
data.frame(
old=x,
new=recode(x, rmat)
)
# Recoding with a data frame
d <- data.frame(from = c(2, 3),
to = c("two", "three") )
data.frame(
old = x,
new = recode(x, d)
)
# Recoding with rule sets
r <- recode(x,
c(1,2), "one or two",
c(3,4), "three or four",
5, "five")
data.frame(old=x, new=r)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.