0

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

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

If the values of a row are zeros, I am getting 1 with max.col(data). But the output should be 0 @Ronak

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.