Jule Jule - 1 month ago 9
R Question

rle command counting changes in vector

n <- length(rle(sign(z)))


z contains 1 and -1. n should indicate the number of how many times the sign of z changes.

The code above does not lead to the desired outcome. If I expand the command to

length(rle(sign(z))[[1]])


it works. I don't understand the underlying mechanism of how [[1]] solves the problem?

Answer

rle returns a list consisting of two components: lengths, and values. As such, its own length is always 2. By contrast, you want to know the length of either of those components (they obviously have the same length). So either length(rle(…)[[1]]) or length(rle(…)[[2]]) would work. Better to use the names instead of an index though, e.g.

length(rle(z)$lengths)

However, this won’t be the number of times the sign changes; rather, it will be the number of times the changes plus 1.