How do I control the row indices in data.table in R?
I want to check if the value in a row matches the previous one:
patient produkt output
1 Meg Initiation
1 Meg Continue
1 Gem Switch
2 Pol Initiation
2 Pol Continue
2 Pol Continue
Where the output column is the output, I wish (could be replaced with numbers if that is easier though such that initiation=0, continue=1, switch=2
).
I can't find out how to control the indices in data.table, and the following does not work
test[ , switcher2 := identical(produkt, produkt[-1]),by=patient]
Any ideas are welcome. It has to be in a data.table though.
Here an option using
diff
. I am usingifelse
to change integer values to characters. Finally , for each group , first element is set to an initial value.