# [R] mean duration (persistence) of daily data

David Winsemius dwinsemius at comcast.net
Mon Jun 21 03:12:34 CEST 2010

On Jun 20, 2010, at 5:52 PM, Schmidt Martin wrote:

> Dear R users
>
> A quite simple question: how can I get the mean duration
> (persistence) of daily data, when the data set looks as follows:
>
> [1] 7 7 7 9 9 5 7 5 5 5 9 5 5 6 6 6 1 1 1 2 2 4 4 4 4 7 7 3 3 2 4 4
> 7 7 7 7 7
> [38] 7 7 5 5 9 9 5 5 5 1 7 9 9 9 9 9 5 5 5 5 5 3 4 4 4 4 4 4 4 4 2 2
> 2 2 2 2 8
> [75] 8 6 6 6 8 8 8 8 8 6 6 2 8 8 8 8 8 8 8 8 8 2 2 2 2 2 6 6 6 6 6 6
> 6 6 6 6 3
> [112] 3 2 2 2 1 5 1 1 4 2 2 2 2 2 2 2 3 4 4 4 3 3 3 6 6 6 8 8 4 4 2
> 4 4 1 1 6 6
> .............................and so on:
>
> Thus, I'd like to know, from each number (1-9) the mean duration
> from the first to the last day (here not visible, but each number
> stands for a day).
>
> With:
>
> length(which(test==1))
>
> I certainly get the total number of number 1......unfortunately
> that's all I got!

I am guessing you want:

?rle

> dur <- scan()
1: 7 7 7 9 9 5 7 5 5 5 9 5 5 6 6 6 1 1 1 2 2 4 4 4 4 7 7 3 3 2 4 4 7 7
7 7 7
38:  7 7 5 5 9 9 5 5 5 1 7 9 9 9 9 9 5 5 5 5 5 3 4 4 4 4 4 4 4 4 2 2 2
2 2 2 8
75:  8 6 6 6 8 8 8 8 8 6 6 2 8 8 8 8 8 8 8 8 8 2 2 2 2 2 6 6 6 6 6 6 6
6 6 6 3
112:  3 2 2 2 1 5 1 1 4 2 2 2 2 2 2 2 3 4 4 4 3 3 3 6 6 6 8 8 4 4 2 4
4 1 1 6 6
149:
> rle(dur)
Run Length Encoding
lengths: int [1:51] 3 2 1 1 3 1 2 3 3 2 ...
values : num [1:51] 7 9 5 7 5 9 5 6 1 2 ...
> mean(rle(dur)\$lengths)
[1] 2.901961

--
Just a guess, mind you. Your problem description seemed vague in both
the input ahd the output sides.

David Winsemius, MD
West Hartford, CT