I\'m facing nested ifelse()
structures:
df1$var <- ifelse(x < a, u, ifelse(x < b, v, ifelse(x < c, w, ...)))
whereby t
I would create an empty vector then fill each condition one by one.
df1$y = rep(NA,nrow(df1))
df1$y[x < a] = u(x[x < a])
df1$y[x > a & x < b] = v(x[x > a & x < b])
df1$y[x > b & x < c] = w(x[x > b & x < c])
...
I have found this to be the clearest way of setting the values, I find it much easier to see at a glance what is happening when you have more conditions than nested ifelse statements.
df1$y = ifelse(x < a, u(x), ifelse(x < b, v(x), ifelse(x < c, w(x), ...)) )
An improvement on this would be to predefine the condition elements, that way each group is only calculated once:
aEls = which(x < a)
bEls = which(x > a & x < b)
cEls = which(x > b & x < c)
...
y = rep(NA,nrow(df1))
y[aEls] = u(x[aEls])
y[bEls] = v(x[bEls])
y[cEls] = w(x[cEls])
...
df$y = y