Nobel
Nobel

Reputation: 1555

Create Matrix of factors from data frame in R

I want to convert a factor data frame, to a factor matrix

But when I try the below code, the type of the matrix is still string

mydata=data.frame(f1=c("yes","yes","no","no"),f2=c("yes","no","no","yes"))
mydata[1:ncol(mydata)]=lapply(mydata[1:ncol(mydata)],factor)

mymatrix=as.matrix(mydata)

#this line didn't help (the matrix still string)
mymatrix=apply(mymatrix,FUN =factor,MARGIN = 2)

Upvotes: 0

Views: 1386

Answers (1)

Umberto
Umberto

Reputation: 1421

Maybe this will get you what you need?

mymatrix = matrix(mydata, ncol = 2)
str(mymatrix)

gives you

List of 2
$ : Factor w/ 2 levels "no","yes": 2 2 1 1
$ : Factor w/ 2 levels "no","yes": 2 1 1 2
- attr(*, "dim")= int [1:2] 1 2

You would need to explain a bit more what you want to do to get more precise help.

Upvotes: 1

Related Questions