简体   繁体   中英

convert a model.matrix in R to a group vector

In R, we can use model.matrix() to construct design matrices, for example,

grp.ids = as.factor(c(rep(1,8), rep(2,4), rep(3,2)))
x = model.matrix(~grp.ids)

gives the design matrix x :

   (Intercept) grp.ids2 grp.ids3
1            1        0        0
2            1        0        0
3            1        0        0
4            1        0        0
5            1        0        0
6            1        0        0
7            1        0        0
8            1        0        0
9            1        1        0
10           1        1        0
11           1        1        0
12           1        1        0
13           1        0        1
14           1        0        1
attr(,"assign")
[1] 0 1 1
attr(,"contrasts")
attr(,"contrasts")$grp.ids
[1] "contr.treatment"

However, if now I am given a design matrix x as above, and hope to get the "grouping vector" grp.ids by somehow manipulating on x . How can I do that? Thanks!

I don't believe you could recover grp.id exactly as it was originally created because it's not possible to tell what the original values of the ids were. You can create a vector that results in the same model.maxtrix though.

factor(apply(x, 1, paste, collapse = "."), labels = seq(ncol(x)))

However, this gets pretty close in this particular case.


The labels for the previous one give the order of 1, 3, 2 (instead of the desired 1, 2, 3) and that is because we get "1.0.0", "1.1.0", "1.0.1" as our actual output and sorted alphanumerically these give the order 1, 3, 2. If we reversed the input string so we had "0.0.1", "0.1.1" and "1.0.1" then this would give the desired order so the following should work

factor(apply(x, 1, function(x){paste(rev(x), collapse = ".")}), labels = seq(ncol(x)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM