[R] comparing elements in a vector
Peter Dalgaard BSA
p.dalgaard at biostat.ku.dk
Wed Sep 18 14:21:47 CEST 2002
Sven Garbade <garbade at psy.uni-muenchen.de> writes:
> Hi all,
>
> there is a vector d which contains three different valus: 0, 1 or 2. I
> wrote a loop which gives me T, when the values in d changed from 1 to
> 2 or from 2 to 1, otherwise F:
>
> for(i in 1:(length(d)-1)) {
> if(d[i] != d[i+1] & d[i] != 0 & d[i+1] != 0)
> change[i+1] <- T
> else
> change[i+1] <- F
> }
>
> This works, but I'm wondering if there is already a R function or an
> easier way to avoid the for-loop.
& and friends vectorize, so
# testdata:
d <- rbinom(30,2,.5)
N <- length(d)
d1 <- d[-N]
d2 <- d[-1]
change <- (d1 != d2) & d1 & d2
# and, just to print and check:
data.frame(d,change=c(NA,change))
--
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list