aledanda wrote:> Hi,
> I need your help.
> I have a vector of numbers reflecting the switch in the perception of a
> figure. For a certain period I have positive numbers (which reflect the
> perception A) then the perception changes and I have negative numbers
> (perception B), and so on for 40000 iterations. I need to take the rate of
> this switch for my analysis. Namely, I need a new vector with numbers which
> reflect how many digit follows in sequence before the change in perception
> (and then I have to take the reciprocal of these numbers in order to obtain
> the rate but is not a problem). For example, suppose that the new vector
> looks like this: new <- c(5,7,8,9) , 5 numbers positive then the
perception
> changes and 7 negative numbers follow, then it changes again and 8 positive
> follows and so on..
> In brief I need to write a little script that detects the change in sign of
> the elements of the vector and count how many positive and how many
negative
> digits there are in sequence.
>
> I would use the for loop, I started but then i don't know how to
continue
>
> rate <- vector()
> for(i in (length(a)) rate <- (a[i]> 0 ????
>
> ..can you help me?
See ?sign and ?rle which together yield:
a <- c(-1, -2, -3, 1, 2, -1)
rle(sign(a))
#Run Length Encoding
# lengths: int [1:3] 3 2 1
# values : num [1:3] -1 1 -1
## or just the vector you want is:
rle(sign(a))$lengths
[1] 3 2 1
Uwe Ligges
> Alessandra
>