Checking for a factor change by group

我怕爱的太早我们不能终老 提交于 2020-01-05 07:23:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!