Reputation: 7051
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.
Upvotes: 2
Views: 130
Reputation: 887851
In base R
, we can use apply
apply(dat == 1, 1, which)
#[1] 1 1 2 3 2 4 3 3
Upvotes: 0