#--------------------------------------
# Numeric vector
x.num <- c(1, 2, 4, 5, 6, 8, 12, 15, 19, 20)
# Recode 5 = 50 and 19 = 190
rec(x.num, "5 = 50; 19 = 190")
# Recode 1, 2, and 5 = 100 and 4, 6, and 7 = 200 and else = 300
rec(x.num, "c(1, 2, 5) = 100; c(4, 6, 7) = 200; else = 300")
# Recode lowest value to 10 = 100 and 11 to highest value = 200
rec(x.num, "lo:10 = 100; 11:hi = 200")
# Recode 5 = 50 and 19 = 190 and check recoding
rec(x.num, "5 = 50; 19 = 190", table = TRUE)
#--------------------------------------
# Character vector
x.chr <- c("a", "c", "f", "j", "k")
# Recode a to x
rec(x.chr, "'a' = 'X'")
# Recode a and f to x, c and j to y, and else to z
rec(x.chr, "c('a', 'f') = 'x'; c('c', 'j') = 'y'; else = 'z'")
# Recode a to x and coerce to a factor
rec(x.chr, "'a' = 'X'", as.factor = TRUE)
#--------------------------------------
# Factor
x.fac <- factor(c("a", "b", "a", "c", "d", "d", "b", "b", "a"))
# Recode a to x, factor levels ordered alphabetically
rec(x.fac, "'a' = 'x'")
# Recode a to x, user-defined factor levels
rec(x.fac, "'a' = 'x'", levels = c("x", "b", "c", "d"))
#--------------------------------------
# Multiple variables
dat <- data.frame(x1.num = c(1, 2, 4, 5, 6),
x2.num = c(5, 19, 2, 6, 3),
x1.chr = c("a", "c", "f", "j", "k"),
x2.chr = c("b", "c", "a", "d", "k"),
x1.fac = factor(c("a", "b", "a", "c", "d")),
x2.fac = factor(c("b", "a", "d", "c", "e")))
# Recode numeric vector and attach to 'dat'
dat <- cbind(dat,
rec(dat[, c("x1.num", "x2.num")], "5 = 50; 19 = 190"))
# Recode character vector and attach to 'dat'
dat <- cbind(dat,
rec(dat[, c("x1.chr", "x2.chr")], "'a' = 'X'"))
# Recode factor vector and attach to 'dat'
dat <- cbind(dat,
rec(dat[, c("x1.fac", "x2.fac")], "'a' = 'X'"))
Run the code above in your browser using DataLab