[R] I know this is wrong, but why?

Thomas Lumley tlumley at u.washington.edu
Fri Aug 2 23:37:22 CEST 2002


On 2 Aug 2002, Stuart Luppescu wrote:

> My mind has become corrupted by having to use SAS too much. I wanted to
> calculate the difference of elements of two vectors if the signs are the
> same. I tried it the corrupted way first:
>
> if (effects1[,3] < 0 & effects0[,3] < 0) {
>   imprv1 <- effects0[,3] - effects1[,3]
> } else  if  (effects1[,3] > 0 & effects0[,3] > 0) {
>   imprv1 <- effects1[,3] - effects0[,3]
> } else {
>   imprv1 <- NA
>
<snip>
> But what I don't understand is why the first method doesn't work, or at
> least why it didn't give me any warning or error messages. Can someone
> enlighten me?

Because if() isn't vectorised.  Eg
> if (1:10<5) "a" else "b"
 [1] "a"

Only the first element is used.

I would have thought there was a good case for a warning here, and I
remember seeing one in the past (though it may have been in S-PLUS 3.x in
the pre-R past).

	-thomas

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list