如何在面板数据中检查受访者是否随时间改变了他们的答案?

How to check whether respondents changed their answers over time in a panel-data?

我正在使用一个面板数据,其中个人随时间被跟踪。我想检查受访者是否从 1 年开始与另一年相比改变了他们的答案。例如,下面的性别变量表示男性为 1,女性为 0。 ID 1 的人在 2005 年和 2006 年之间将他们的答案从男性更改为女性。

因为我的 data.frame 中有数百万人,我想创建一个变量,为随时间改变答案的受访者提供 9 的值,为那些已经改变答案的受访者提供 8 的值不断的回应。有人可以指导我如何使用 dplyr 实现吗?

id  year    unemployment       change
1   2005        1                 9
1   2006        0                 9
1   2007        0                 9
2   2007        1                 8
2   2008        1                 8

structure(list(id = structure(c(1, 1, 1, 2, 2), format.stata = "%9.0g"), 
    year = structure(c(2005, 2006, 2007, 2007, 2008), format.stata = "%9.0g"), 
    unemployment = structure(c(1, 0, 0, 1, 1), format.stata = "%9.0g"), 
    change = structure(c(9, 9, 9, 8, 8), format.stata = "%9.0g")), row.names = c(NA, 
-5L), class = c("tbl_df", "tbl", "data.frame"))

如果我们假设我们需要检测失业率的变化,而不是性别,我们可以使用类似的东西:

d %>% 
  group_by(id) %>% 
  mutate(change = ifelse(n_distinct(unemployment) == 1, 8, 9))

但是,我不建议使用 8 和 9 这样的值来编写这样的变化变量,因为它不容易理解。