简体   繁体   中英

How to convert a binary data frame to a vector?

Suppose I have a data frame such like

dat<-data.frame('0'=c(1,1,0,0,0,0,0,0),
                '1'=c(0,0,1,0,1,0,0,0),
                '2'=c(0,0,0,1,0,0,1,1),
                '3'=c(0,0,0,0,0,1,0,0))
dat
  X0 X1 X2 X3
1  1  0  0  0
2  1  0  0  0
3  0  1  0  0
4  0  0  1  0
5  0  1  0  0
6  0  0  0  1
7  0  0  1  0
8  0  0  1  0

I wanted to convert it to a vector like 1,1,2,3,2,4,3,3 where the numbers corresponding the column-th with unit 1 . For example, 4 means the col 4th on row number 6th is 1.

Use

max.col(dat)
# [1] 1 1 2 3 2 4 3 3

In base R , we can use apply

apply(dat == 1, 1, which)
#[1] 1 1 2 3 2 4 3 3

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