问题
I have a data.table as follows:
library(data.table)
DT <- fread(
"Event_Type country year
A NLD 2005
B NLD 2004
A GBR 2006
B GBR 2003
A GRC 2002
A GRC 2007",
header = TRUE)
From this post, I know I can see if there is a change in event type as follows:
ind <- with(DT, c(FALSE, Event_Type [-1L]!= Event_Type [-length(Event_Type )]) & Event_Type !='NULL')
DT$switch <- ifelse(ind, 1, '')
But I would like to be able to do this by group as well, in this case the country
. How can I do this?
回答1:
If you're using data.table, you can use the shift
function to create a lagged variable and check if event is equal to its lagged value.
DT[, switch := Event_Type != shift(Event_Type, fill = Event_Type[1]), country]
That creates the ind
part of your code, if you want something other than TRUE/FALSE you can put it in an ifelse
(or fifelse
if you're on a recent data.table version).
来源:https://stackoverflow.com/questions/59073241/checking-for-a-factor-change-by-group