按组检查因素变化 [英] Checking for a factor change by group
问题描述
我有一个data.table如下:
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?
推荐答案
如果您使用的是data.table,则可以使用 shift
函数创建一个滞后变量,并检查事件是否等于其滞后值。
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]
这会在代码中创建 ind
部分,如果您需要除TRUE / FALSE之外的其他内容,可以将其放入 ifelse
(如果您使用的是最新的data.table版本,则为 fifelse
)。
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).
这篇关于按组检查因素变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!