question R regarding consecutive numbers
On Oct 27, 2011, at 9:21 AM, Duncan Murdoch wrote:
On 27/10/2011 8:43 AM, Samir Benzerfa wrote:
Hi everyone Do you know about any possibility in R to check for consecutive numbers in vectors? That is, I do not only want to count the number of observations in total (which can be done table(x)), but I also want to count for instance how many times that vector contains a certain number consecutively. For example in the following vector x the number "1" appears 7 times. However, I want to check for instance how many times two consecutive 1's appear in the vector, which would actually be two times the case in the below vector.
x=c(1,1,3,4,9,1,9,1,5,4,5,2,1,1,1,6)
Any ideas for this issue?
How about this?
runs <- rle(x) with(runs, table(values, lengths))
And to go even a bit further, the table function returns a matrix which can be addressed to yield the specific answer requested: with(runs, table(values, lengths))["1",2] [1] 1 # m=number of exactly runs if length 2 > sum( tbl["1", 2:ncol(tbl)] ) [1] 2 # number of runs of length two or more.
David > > lengths > values 1 2 3 > 1 2 1 1 > 2 1 0 0 > 3 1 0 0 > 4 2 0 0 > 5 2 0 0 > 6 1 0 0 > 9 2 0 0 > > Duncan > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. David Winsemius, MD West Hartford, CT