0

I'm trying to add a number to a vector if it passes a test. Why is this not working? I'm using R.

good_vect <- ifelse(passed_assump1==TRUE&passed_assump2==TRUE&strong==TRUE&self_sust==TRUE,c(good_vect,strat_num),c(good_vect))

or

valuable_strat_vect <- ifelse((master_strat_vect[13*j])>=cutoff_coop_ratio,c(valuable_strat_vect,j),c(valuable_strat_vect))

It spits out this error:

Error in ifelse((master_strat_vect[13 * j]) >= cutoff_coop_ratio, c(valuable_strat_vect,  : 
  replacement has length zero
In addition: Warning message:
In rep(no, length.out = length(ans)) :
  'x' is NULL so the result will be NULL
  • It's not clear what you want to do without knowing the dimensions of the things you're passing in. `ifelse` **always** returns a value *of the same shape as the first argument* (the test). If your tests are all of length 1, you will get output of length 1--and you should probably use `if(){}else{}` not `ifelse()`. See `?ifelse` for details. – Gregor Thomas Oct 13 '16 at 21:00
  • With that understanding of `ifelse`, your outputs don't make sense, as they seem to have their lengths differ based on the outcome. This is not possible with `ifelse`. – Gregor Thomas Oct 13 '16 at 21:01
  • Probable duplicate: [Why can't R's ifelse return vectors?](http://stackoverflow.com/q/1335830/903061) – Gregor Thomas Oct 13 '16 at 21:02
  • 1
    One other note: `==TRUE` is almost never needed, and if your conditions all have length 1, then `all()` is nicer than `... & ... &...`, you could rewrite your first line as `if(all(passed_assump1, passed_assump2, strong, self_sust)) good_vect <- c(good_vect, strat_num)`. Since `good_vect` is already itself, the `else` is unnecessary as well. – Gregor Thomas Oct 13 '16 at 21:07

0 Answers0