0

I want to create a dummy where all cells that include NA become 1 and all other cells -1. I tried to different things both not resulting in my desired outcome.

1) This leads to only NA Values.

Cox.Reg$FirstTask <- ifelse(Cox.Reg$active_task_avg_depth == NA, 1, -1)

2) This leads to only the -1 values being shown in the new column.

Cox.Reg$FirstTask <- ifelse(Cox.Reg$active_task_avg_depth == "NA", 1, -1)  
Amy
  • 91
  • 1
  • 12

1 Answers1

4

If it is a real NA, then we can use is.na to detect the NA elements, which would return TRUE for all NA and FALSE for others as a logical vector, which can be used in ifelse to change the values

ifelse(is.na(Cox.Reg$active_task_avg_depth), 1, -1)

Or another option is to create a numeric index and change the values accordingly

c(-1, 1)[is.na(Cox.Reg$active_task_avg_depth) + 1]
akrun
  • 874,273
  • 37
  • 540
  • 662
  • I have another question, now i want to create a dummy variable if the cell value is 1 to 7, then the dummy variable should be 1 else -1. I tried to solve it like this but it does not work.. Thank you in advance! Cox.Reg$FirstTask <- if((Cox.Reg$dayofmonth_created >=1 && Cox.Reg$dayofmonth_created <=7) 1, -1) – Amy Dec 08 '19 at 18:11
  • 1
    @Amy INn that case you can either use `%in%` or `>=/<=` but with `&` and not `&&` i..e. `ifelse(Cox.Reg$dayofmonth_created >=1 &Cox.Reg$dayofmonth_created <=7, 1, -1)` – akrun Dec 08 '19 at 18:13
  • One last question, what would i do if i have variables that need a baseline. eg. they can be for example when i want to know which day of the week, so i would need the output to be binary yet still show me on which day it was created – Amy Dec 08 '19 at 18:30
  • 1
    @Amy In that case, it would be better to have it as logical `is.na(Cox.Reg$active_task_avg_depth)` because you can wrap with `which(is.na(Cox.Reg$active_task_avg_depth))` to find the position always – akrun Dec 08 '19 at 18:32
  • Hi @akrun can you please help me with this https://stackoverflow.com/questions/59233401/in-r-how-to-create-multilevel-radiogroupbuttons-as-each-level-depends-choicena?noredirect=1#comment104681894_59233401 – John Smith Dec 08 '19 at 18:41
  • 1
    Yet another way: `2*is.na(Cox.Reg$active_task_avg_depth) - 1`. – Rui Barradas Dec 08 '19 at 19:20