Skip to content
Prev 308438 / 398513 Next

Matrix to data.frame with factors

On Oct 19, 2012, at 16:07 , Rui Barradas wrote:

            
Another way, possibly more easily generalized:

x <- matrix(sample(0:1, 12, TRUE), ncol = 4)
y <- as.data.frame(x)
y[] <- lapply(y, factor, levels=0:1)
str(y)

with extensions like

is01 <- function(x) all(na.omit(x) %in% 0:1)
x <- matrix(sample(0:1, 12, TRUE), ncol = 4)
y <- as.data.frame(x)
ix <- sapply(y, is01)
y[ix] <- lapply(y[ix], factor, levels=0:1, labels=c("n","y"))
str(y)