Find change index in column

Is there a way to find the change indices of factors in a column with R? For example:

x <- c("aaa", "aaa", "aaa", "bbb", "bbb", "ccc", "ddd")

will return 3, 5, 6

+4
source share
3 answers

You can try to compare shifted vectors, for example.

which(x[-1] != x[-length(x)])
## [1] 3 5 6

This will work on both symbols and factors.

+8
source
which(!!diff(as.numeric(x)))
[1] 3 5 6

It is assumed that you really have factors. They are stored internally with numerical values. Therefore, when a difference is made, each will take place with every change. The second coercion is that zeros are considered FALSE and other TRUE numbers. whichfinds the TRUE values ​​of aka non-zeroes.

+4
source

rle :

head(cumsum(rle(x)$lengths), -1)
[1] 3 5 6
+3

Source: https://habr.com/ru/post/1606656/


All Articles