Skip to content
Prev 173589 / 398506 Next

Taking diff of character vectors

Hello, everybody

Say I have
nm1 <- c(rep(1,10), rep(0,10))
then I can do:
diff(nm1)
to see where I have shift in value

but what if I have
nm2 <- c(rep("SPZ8", 10), rep("SPX9", 10))

how can I produce the same ouput as diff(nm1) does, that is zeros
everywhere except for one place where SPZ8 changes to SPX9 (there
should be 1 there)?

What if I have a matrix of characters like that:
nm3 <- c(rep("GLF9", 4), rep("GLF10", 16))
matr <- cbind(nm2, nm3)

How can I efficiently create two more columns that contain zeros
everywhere except for place where there is shift in character values?

Thanks for help!
Sergey