# r - 在涉及因素的情况下用向量创建矩阵

## Creating a matrix with vectors, when there are factors involved

I almost reached the end of the internet, but I couldn't find the (exact) answer to my question!

It's probably very easy, but I just want to select some variables from a dataframe, to form a matrix with some of its vectors. So mainly what happend is printed in my example below:

``````treatment <- factor(rep(c(1, 2), c(43, 41)), levels = c(1, 2),
labels = c("placebo", "treated"))

improved <- factor(rep(c(1, 2, 3, 1, 2, 3), c(29, 7, 7, 13, 7, 21)),
levels = c(1, 2, 3),
labels = c("none", "some", "marked"))

numberofdrugs<-rpois(84, 2)

X<-cbind(numberofdrugs, treatment, improved)

X #"why are the units numbers and not names
``````

The problem that I've got is, that R is converting factors to numbers. For example "male" and "female" to "0" and "1". But I don't want that! What am I supposed to do?

This is documented behaviour of `cbind`. From `?cbind`: "Any classes the inputs might have are discarded (in particular, factors are replaced by their internal codes.)"

You should use `data.frame` instead:

``````X <- data.frame(numberofdrugs, treatment, improved)

numberofdrugs treatment improved
1             0   placebo     none
2             1   placebo     none
3             0   placebo     none
4             5   placebo     none
5             1   placebo     none
6             4   placebo     none
``````

``````treatment <- factor(rep(c(1, 2), c(43, 41)), levels = c(1, 2),
labels = c("placebo", "treated"))

improved <- factor(rep(c(1, 2, 3, 1, 2, 3), c(29, 7, 7, 13, 7, 21)),
levels = c(1, 2, 3),
labels = c("none", "some", "marked"))

numberofdrugs<-rpois(84, 2)

X<-cbind(numberofdrugs, treatment, improved)

X #"why are the units numbers and not names
``````

``````X <- data.frame(numberofdrugs, treatment, improved)