[R] Finding and manipulation clusters of numbers in a sequence of numbers

mdvaan mathijsdevaan at gmail.com
Mon Jul 16 18:17:43 CEST 2012


Hi,

I have the following sequence:
in <- c(0, 0, 0, 2, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 0, 2, 0, 0, 2)

>From this sequence I would like to get to the following sequence:
out <- c(0, 0, 0, 3, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0,
0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 0, 2, 0, 2, 0, 0, 2)

Basically, what I would like to do for each number greater than 0,  is to
add all adjacent numbers and the adjacent numbers of those numbers, etc.
until one of those numbers is equal to 0.

I could manually repeat the loops below until "sequence" stops changing but
there must be a smarter way. Any suggestions? Thanks!

sequence <- c(0, 0, 0, 2, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0,
0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 0, 2, 0, 0, 2)
    for (h in 2:(length(sequence) - 1))
      {
      sequence[h] <- ifelse(sequence[h] > 0, sequence[h-1] + sequence[h], 0)
      }
    
    for (h in 1:(length(sequence) - 1))
      {
      sequence[h] <- ifelse(sequence[h] > 0 & sequence[h+1] > sequence[h],
sequence[h+1], sequence[h])
      }  

--
View this message in context: http://r.789695.n4.nabble.com/Finding-and-manipulation-clusters-of-numbers-in-a-sequence-of-numbers-tp4636661.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list