n <- length(rle(sign(z)))
rle returns a list consisting of two components:
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(…)[]) would work. Better to use the names instead of an index though, e.g.
However, this won’t be the number of times the sign changes; rather, it will be the number of times the changes plus 1.