0

I am trying to write the following script but I am only getting 7 or 40 back even thought the condition to satisfy all other variables exists. I am not very good with looping so I am not sure how to write this:

Input2$SetUpTime<-  
    if_else(Input2$finished_surface_area_inches <   10,  "5",
    if_else(Input2$finished_surface_area_inches <   60,  "7",
    if_else(Input2$finished_surface_area_inches <  200, "10",
    if_else(Input2$finished_surface_area_inches < 1000, "20",
    if_else(Input2$finished_surface_area_inches < 4000, "40", NA)))))
DanY
  • 5,920
  • 1
  • 13
  • 33
Toney Honar
  • 57
  • 2
  • 3
  • 1
    Perhaps `dplyr::if_else`? (It is helpful to include all non-base packages, explicitly via `library(dplyr)` in your sample code.) – r2evans Aug 06 '18 at 17:51
  • 2
    We will never know for certain how to help since we do not know the structure of `Input2`. In general, though, when I find myself considering nested `ifelse`/`if_else`, I also consider `dplyr::case_when`, which can have the same effect while being considerably easier to read/maintain. – r2evans Aug 06 '18 at 17:53
  • 1
    Hi @toney-honar, welcome to Stackoverflow. Please consider making a reproducible example. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Ricardo Saporta Aug 06 '18 at 17:53
  • yes i did use ifelse and it didn't work so i tried if_else – Toney Honar Aug 06 '18 at 17:53
  • In basic usage, `if_else` adds no capability over `ifelse`. What it offers is *safety*, where it enforces identical classes between the true/false vectors. (It does offer the `missing=` argument, but that might not be necessary in your usage.) – r2evans Aug 06 '18 at 17:55
  • 2
    Toney, if you paste the output of `dput(head(Input2))` into your question, we might be able to better inform your problem. (Also add actual and expected output from your code.) – r2evans Aug 06 '18 at 17:57

1 Answers1

2

The dplyr::if_else() function requires that the TRUE and FALSE return values are of the same type. We can see that, e.g., "5" and NA are not of the same type:

typeof("5")
[1] "character"

typeof(NA)
[1] "logical"

One simple fix is to change NA to NA_character_:

typeof(NA_character_)
[1] "character"

Beyond that, you might be getting unexpected results because you are feeding-in unexpected data. The following shows that your nesting will work on "expected" data:

library(dplyr)
somedata <- c(9, 59, 199, 999, 3999, 4001)

res <- if_else(somedata <   10,  "5",
       if_else(somedata <   60,  "7",
       if_else(somedata <  200, "10",
       if_else(somedata < 1000, "20",
       if_else(somedata < 4000, "40", NA_character_)))))

res
[1] "5"  "7"  "10" "20" "40" NA
DanY
  • 5,920
  • 1
  • 13
  • 33