0

simple question. I want to add bracket for column b as per below. I tried ifelse but only gets the final one and i do not know how to nest it?

a <- c(1,2,3,4,5)
b <- c(5,10,15,16,17)
bracket <- c("5 - 10 days", "10-15 days","10-15 days", "More then 15", "More then 15")
df <- data.frame(a,b,bracket)

So the result is 'bracket' column.

I tried below with no luck

df$bracket <- ifelse (df$b> 15 ,"More then 15",NA)
df$bracket <- ifelse (df$b <= 15 & df$b > 10,"10-15 days",NA)
df$bracket <- ifelse (df$b <= 10 & df$b > 5,"5 - 10 days",NA)
Kalenji
  • 401
  • 2
  • 19
  • 42
  • 1
    I'd say better to use `cut` when just dividing something into ranges. In this case, `df$bracket = cut(df$b, breaks = c(-Inf, 5, 10, 15, Inf), labels = c(NA, "5 - 10 days", "10 - 15 days", "More than 15"))` – Gregor Thomas Jun 13 '19 at 20:39
  • I guess OP is looking to learn `nested if` statements – Jason Mathews Jun 13 '19 at 20:43
  • 1
    The issue with your approach is that you overwrite the whole column each time. Each piece works, but (re)sets the others to `NA`. The way to nest it would be `ifelse(df$b > 15, "More than 15", ifelse(df$b > 10, "10 - 15 days", ifelse(df$b > 5, "5 - 10 days", NA)))` – Gregor Thomas Jun 13 '19 at 20:44
  • I'd add that, while it's valuable to understand and be able to use nested `ifelse` when appropriate, if you are nesting more than 2 or 3 conditions it gets messy and there's *usually* a better way. See, for example [Nested ifelse is the worst, what's the best?](https://stackoverflow.com/q/30088919/903061). In many cases, `dplyr`'s `case_when` can be just as general and much more readable. – Gregor Thomas Jun 13 '19 at 20:52

0 Answers0