Kingindanord
Kingindanord

Reputation: 2036

Loops and counting in R

I want to count how many times the numbers in the data set reaches a limt (let it be 8 and -8) after it returned to 0 in the attachment you can see a graph that explains my question better. so with this set of data it should be 6 times. can you please tell me how can I code it in R, or which functions should I read in order to do it my self.

Data set:enter image description here {1 0 -8 -1 5 3 0 -9 -9 -8 0 7 -6 4 -4 5 -5 0 8 -6 8 -2 8 0 2 7 6 0 -8 -8 }

Upvotes: 1

Views: 165

Answers (1)

Christoph
Christoph

Reputation: 7063

Some ideas:

a <- c(1,0,-8,-1,5,3,0,-9,-9,-8,0,7,-6,4,-4,5,-5,0,8,-6,8,-2,8,0, 2,7,6,0,-8,-8) 
b <- split(a,cumsum(a==0)) # b is of class list. The names of the elements names(b) are '1', '2', ...

found <- 0
for (i in 1:length(names(b))) { # iterate over all elements names(b)[i]
  if (sum(abs(b[[names(b)[i]]]) >= 8) > 0) { # i th part b[[names(b)[i]]]
    found <- found + 1 # if there is an entry >8 or <-8 increase counter
  }
}

Upvotes: 1

Related Questions