s-news
[Top] [All Lists]

Re: running sum of counts

To: Tim Wade <wade_tj@yahoo.com>
Subject: Re: running sum of counts
From: Tim Hesterberg <timh@insightful.com>
Date: 19 Apr 2004 12:04:06 -0700
Cc: s-news@lists.biostat.wustl.edu
In-reply-to: <20040419181637.93727.qmail@web12307.mail.yahoo.com> (message from Tim Wade on Mon, 19 Apr 2004 11:16:36 -0700 (PDT))
References: <20040419181637.93727.qmail@web12307.mail.yahoo.com>
>I have what I'm sure is a very simple question.
>
>I have a vector like this:
>
>1 1 1 1 2 2 2 3 3 4 4 4 4 4 5 5 5 5 5 6 7 3 3 3 2 2.
>
>I would like to generate a sequence consisting of a
>running sum of count values, like this:
>
>1 2 3 4 1 2 3 1 2 1 2 3 4 5 1 2 3 4 5 1 1 1 2 3 1 1.

unlist(lapply(rle(x)$lengths, seq))

There are two parts to this:
(1)
        rle(x)$lengths
counts the repetitions.

(2) unlist(lapply(  y  , seq))
converts c(4, 3, ...)
into c(1:4, 1:3, ...)

Tim Hesterberg

P.S.  rle() and the flexibility of lapply are two tricks I talk about
in my Advanced Programming class.  Next one is in Zürich.

========================================================
| Tim Hesterberg       Research Scientist              |
| timh@insightful.com  Insightful Corp.                |
| (206)802-2319        1700 Westlake Ave. N, Suite 500 |
| (206)802-2500 (fax)  Seattle, WA 98109-3044, U.S.A.  |
|                      www.insightful.com/Hesterberg   |
========================================================
Download the S+Resample library from www.insightful.com/downloads/libraries

I'll teach classes in Zürich:
        17-18 May:  Advanced Programming Methods in S-PLUS
           19 May:  Bootstrap Methods and Permutation Tests
See http://www.insightful.com/services/intl_training.asp


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