[R] function recode within sapply

Lara Poplarski larapoplarski at gmail.com
Mon Oct 3 07:16:30 CEST 2011


Dear List,

I am using function recode, from package car, within sapply, as follows:

L3 <- LETTERS[1:3]
(d <- data.frame(cbind(x = 1, y = 1:10), fac1 = sample(L3, 10,
replace=TRUE), fac2 = sample(L3, 10, replace=TRUE), fac3 = sample(L3,
10, replace=TRUE)))
str(d)

d[, c("fac1", "fac2")] <- sapply(d[, c("fac1", "fac2")], recode,
"c('A', 'B') = 'XX'", as.factor.result = TRUE)
d[, "fac3"] <- recode(d[, "fac3"], "c('A', 'B') = 'XX'")
str(d)

However, the class of columns fac1 and fac2 is "character" as opposed
to "factor", even though I specify the option "as.factor.result =
TRUE"; this option works fine with a single column.

Any thoughts?

Many thanks,
Lara



More information about the R-help mailing list