s-news
[Top] [All Lists]

re: [S] Looping

To: s-news@wubios.wustl.edu
Subject: re: [S] Looping
From: Scott.Chasalow@USERS.PV.WAU.NL
Date: Fri, 21 Aug 1998 11:28:26 +0200
Cc: lars@ana.unibe.ch
Reply-to: Scott.Chasalow@USERS.PV.WAU.NL
Sender: owner-s-news@wubios.wustl.edu
On Fri Aug 21 09:12:03 1998,
Lars Karlsson <lars@ana.unibe.ch> wrote:
>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.
...
>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

Hi,

I would work with the indices of the ones, as in this function:

> "spacing" <-
function(x, value = 1)
{
# DATE WRITTEN:  21 Aug 1998     LAST REVISED:  21 Aug 1998
# AUTHOR:  Scott D. Chasalow  (Scott.Chasalow@users.pv.wau.nl)
#
# DESCRIPTION:
#       Count how many times x[j] and x[j + i] both equal value, 
#       j = 1,...,length(x);  i = 0,...,length(x)-j.
#
#       Returns an integer vector of length length(x), with one
#       element for each value of i in 0,...,length(x)-1.
# 
        pos <- seq(along = x)[x == value]
        if(length(pos) == 0)
                return(rep(0, length(x)))
        out <- outer(pos, pos, "-")
        out <- out[lower.tri(out, diag = T)]
        tabulate(out + 1, nbins = length(x))
}

> vec
 [1] 1 0 1 1 2 1 2 1 0 1

> spacing(vec)
 [1] 6 1 4 2 2 2 1 2 0 1

> spacing(vec, 0)
 [1] 2 0 0 0 0 0 0 1 0 0

> spacing(vec, 2)
 [1] 2 0 1 0 0 0 0 0 0 0

Cheers,
Scott
=========================================
Scott.Chasalow@users.pv.wau.nl

Wageningen Agricultural University
Laboratory of Plant Breeding
P.O. Box 386
6700 AJ Wageningen
THE NETHERLANDS

http://www.spg.wau.nl/pv/staff/Chasal_S.htm
===========================================
-----------------------------------------------------------------------
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

<Prev in Thread] Current Thread [Next in Thread>