I´m trying get a piecewise regression.

for(i in 1:length(Velocidad)){
  if(Velocidad[i]< vmin)
  if(Velocidad[i]>vmin && Velocidad[i]< vmax)
  if(Velocidad[i]< vmax)

Warning: number of items to replace is not a multiple of replacement length

Any idea as to how predict between the limits?

** I can't use the explicit equation because its order depends on other function


1 Answer 1


Use vector arithmetic:

pred.pot <- (Velocidad < vmin) * 0 +
            (Velocidad >= vmin & Velocidad <= vmax) * predict(reg) +
            (Velocidad < vmin) * 2000

or a vectorized ifelse

pred.pot <- ifelse(Velocidad < vmin, 0,
                ifelse(Velocidad >= vmin & Velocidad <= vmax,  predict(reg),

Don't loop over atomic vectors in R unless you really need to (though lists are another thing entirely). Don't use <<- unless you really need to. If you're ever wondering if you really need to do either of these things, you don't need to.

Finally, always use brackets, even in single line if statements.

  • $\begingroup$ If you wondering why you should always use brackets, this bug in apple's ssl code is an exemplar of why omitting them is an error: nakedsecurity.sophos.com/2014/02/24/… $\endgroup$ Apr 2, 2017 at 23:54
  • $\begingroup$ Thank you for your advices but now i get this warning: In (Velocidad >= vmin & Velocidad <= vmax) * predict(reg) : longer object length is not a multiple of shorter object length $\endgroup$
    – Alex
    Apr 2, 2017 at 23:58
  • $\begingroup$ That error is pretty clear to me. It means the length of the Velcidad vector is not the same as the predict(reg) vector. You'll have to fix that yourself, as you did not provide context for what these vectors are. $\endgroup$ Apr 2, 2017 at 23:59
  • $\begingroup$ Thank you for your help, I've already found my fail and it's solved. $\endgroup$
    – Alex
    Apr 3, 2017 at 14:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.