Skip to content
Prev 257375 / 398506 Next

Several factors same levels

On Apr 19, 2011, at 10:57 , dereksloan wrote:

            
Yes, if they are in the same data frame. The idiom goes roughly like this

ix <- c("alcohol", "smoker")
new <- paste("f", ix, sep="")
dd[new] <- lapply(dd[ix], factor, levels=0:1, labels=c("No","Yes"))

(You might store the transformed variables back where they came from, just make sure to do it exactly once! That would avoid creating new variable names and give you a bit more flexibility in the choice of index type. There are also various possibilities to actually compute the indices, e.g.

isBin <- function(x) all(na.omit(x) %in% 0:1)
ixl <- sapply(dd, isBin)
ix <- names(dd)[ixl]
...
)