[S] Looping

Lars Karlsson (lars@ana.unibe.ch)
Fri, 21 Aug 1998 09:12:03 +0200


Is there a way to avoid the loops below?
vec is a vector of length n. I want to count the number of instances
where an element and the next j-th element both equals 1.

n <- length (vec)
aaa <- rep (0, n)
for (j in 0:(n-1)){
aa <- 0
for (i in 1:(n - j)){
if ( vec[i] == 1 & vec[i+j] == 1 ) aa <- aa + 1
}
aaa[j+1] <- aa
}

For example:
> vec <- c(1,0,1,1,2,1,2,1,0,1)
yields
> aaa
[1] 6 1 4 2 2 2 1 2 0 1

Thanks in advance for any help.
/Lars

----------------------------------------------------------
Tekn.Dr. Lars M. Karlsson Tel: +41 (0)31 631 84 52
Department of Anatomy Fax: +41 (0)31 631 34 10
University of Berne mailto:Lars@ana.unibe.ch
Buelstrasse 26
CH-3000 Berne 9
Switzerland
http://www.ana.unibe.ch/ANATOM/staff/karlsson/index.html

----------------------------------------------------------
-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message: unsubscribe s-news