Skip to content

function recode within sapply

2 messages · Lara Poplarski, Joshua Wiley

#
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
#
Hi Lara,

Use lapply here instead of sapply or specify simplify = FALSE.  See
?sapply for details.

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

Cheers,

Josh
On Sun, Oct 2, 2011 at 10:16 PM, Lara Poplarski <larapoplarski at gmail.com> wrote: