0

I need R to create a new categorical variable using three dummies that I have in my dataset. I am trying to use "if" and "else if". I have managed to do it in other sotfware but I can't find the solution in R. Would someone please take a look at my code and tell me what's wrong?

    data$newvariable<- if(data$dummyA[1]) {
   (data$newvariable<-"1")
    } else if(data$dummyB[1]){
    (data$newvariable<-"2")
    } else if(data$dummyC[1]){
    (data$newvariable<-"3") }

I hope not to duplicate questions. Sorry! And thank you in advance!

What I get as a result is all cases categorized as "1", which makes me think there is something missing between the first if statement and the following one. But I can't find the solution, help, please!

THANKS!

Anita-
  • 21
  • 7
  • 1
    When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. This will make it easier to help you. – MrFlick Aug 07 '18 at 14:11
  • 1
    `if` checks a single condition - probably you want to use the vectorized version `ifelse`, something like `data$newvar = with(data, ifelse(dummyA, 1 ifelse(dummyB, 2, 3)))`. You could also try `dplyr::case_when` if you are using `dplyr`. – Gregor Thomas Aug 07 '18 at 14:12
  • Waiting to confirm, but suggested dupe: [vectorized if statement in R](https://stackoverflow.com/q/4042413/903061). – Gregor Thomas Aug 07 '18 at 14:13
  • It worked with ifelse! It was what I was looking for =) – Anita- Aug 07 '18 at 14:28

1 Answers1

0

You can use ifelse() to do the job.

 data$newvariable <- ifelse(data$dummyA[1], "1", 
                             ifelse(data$dummyB[1], "2",
                                    ifelse(data$dummyC[1], "3")))

This should work, but can not test it without a reproducible example.

Wenlong Liu
  • 444
  • 2
  • 13