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

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Fri Aug 2 23:41:08 CEST 2002

Stuart Luppescu <s-luppescu at uchicago.edu> writes:

> 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
>
> Then I realized it was giving me wrong results, (for one thing, I was
> getting no NAs) and I should be doing it ``The R Way'' like this:
>
> imprv1 <- rep(NA, 267)
> imprv1[effects1[,3] < 0 & effects0[,3] < 0] <-  effects0[,3] - \
> effects1[,3]
> imprv1[effects1[,3] > 0 & effects0[,3] > 0] <-  effects1[,3] - \
> effects0[,3]
>
> 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?

The main thing is that R generally deals in entire vectors and that
if-statements will only make one decision, never do one thing for some
elements and something else for the rest. In  if (effects1[,3] < 0 &
effects0[,3] < 0)  the condition is a vector. but only the first
element is used, as in

> X <- c(T,T,F)
> if (X) X else !X
[1]  TRUE  TRUE FALSE
> X <- c(F,T,F)
> if (X) X else !X
[1]  TRUE FALSE  TRUE

for by-element decisions consider ifelse(), or, as you did, indexing.

--
O__  ---- Peter Dalgaard             Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics     2200 Cph. N
(*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._