user1477388
user1477388

Reputation: 21430

cbind factor vector with level names

I create three vectors and try to combine them into one table using cbind. The third vector is a factor with three levels. I get this output:

 v1 <- c(1,2,3)
 v2 <- c(4,5,6)
 v3 <- factor(c('lorem','ipsum','dolor'))
 cbind(v1,v2,v3)
     v1 v2 v3
[1,]  1  4  3
[2,]  2  5  2
[3,]  3  6  1

Preferred output would be:

 cbind(v1,v2,v3)
     v1 v2 v3
[1,]  1  4  lorem
[2,]  2  5  ipsum
[3,]  3  6  dolor

Is it possible to get the level names instead of the ID to display as above?

Upvotes: 1

Views: 2278

Answers (1)

akrun
akrun

Reputation: 887048

Not sure about why you need to do this way. It is better to use data.frame which can hold multiple classes. By using cbind, we get a matrix and a matrix can hold only a single class. So, even if there is a single non-numeric value, the columns are all transformed to 'character' class.

 cbind(v1, v2, v3=levels(v3)[v3])
 #     v1  v2  v3     
 #[1,] "1" "4" "lorem"
 #[2,] "2" "5" "ipsum"
 #[3,] "3" "6" "dolor"

Or

 cbind(v1, v2, v3=as.character(v3))

Upvotes: 2

Related Questions