简体   繁体   中英

creating conditional variable in R

For the following data set

> data
   x1 x2 x3
1   1  0  0
2   0  1  0
3   0  0  1
4   0  0  1
5   1  0  0
6   0  1  0
7   1  0  0
8   0  1  0
9   0  0  1
10  1  0  0

I would like to create new variable z such that it takes 1 if x1=1 , 2 if x2=1 and 3 if x3=1 , z will look like z=c(1,2,3,3,1,2,1,2,3,1) . Any help is appreciated

Assuming there will be only one 1 in a given row as shown in the data shared, we can use max.col

data$z <- max.col(data)
data
#   x1 x2 x3 z
#1   1  0  0 1
#2   0  1  0 2
#3   0  0  1 3
#4   0  0  1 3
#5   1  0  0 1
#6   0  1  0 2
#7   1  0  0 1
#8   0  1  0 2
#9   0  0  1 3
#10  1  0  0 1

In case of multiple 1's in a given row explore the ties.method in ?max.col which gives an option to get "first" or "last" 1.

If we want to return 0 if all the row values are 0 we can do:

data$z <- max.col(data) * +(rowSums(data == 1) > 0)

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