R:如何统计长度条件的纵向数据库中连续出现的次数?

R: How to count the number of consecutive occurrences in a longitudinal database with a length condition?

我在 R 上使用一个关于个人的纵向数据库,每个 ID 有几行(在数据库中命名为 vn),他们的属性在列中。我的变量 observation 表示观察的每一年,maritalstatus 表示此人是否已婚 1 或未 0

这是我数据库中个人的概览:

structure(list(vn = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), maritalstatus = c(0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1), observation = c(2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018)), class = "data.frame")

我正在寻找一种方法来创建一个新变量,该变量仅在它们的长度第一次大于或等于 5 时才计算连续出现的次数。对于此示例,它将是:

marital_length = c (0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0)

我当前的代码(如下)创建了一个变量来计算连续数字的最大长度,但我没有找到一种方法来添加条件以仅在第一次长度为 >= 5 时进行计数。


maritalstatus_consecutive <- tapply(test$maritalstatus, INDEX = test$vn, most_consecutive_val)```

test$marital_length <- maritalstatus_consecutive[test$vn]

我也尝试使用 min()(而不是最大值)但是例如,如果一个人结婚 2 年,离婚,然后结婚 6 年,我将无法在这个新变量中看到如果我不添加条件 >=5.

她已经结婚 6 年了

有没有人知道可以帮助我的代码?

也许这太复杂了,但似乎有效:

df$marital_length <- with(df, ave(maritalstatus, vn, FUN = function(x) 
                with(rle(x), rep(as.integer(seq_along(lengths) == 
                     which.max(lengths >= 5)) * lengths, lengths))))


df$marital_length
#[1] 0 0 0 0 0 0 5 5 5 5 5 0 0 0 0 0 0 0 0

which.max(lengths >= 5)首次给出长度大于5的索引

我不完全确定您的预期输出试图表示什么。如果你只想要第一次婚姻的长度 >=5 年 vn 你可以使用

tapply(df$maritalstatus, df$vn, function(x) with(rle(x), lengths[lengths >= 5][1]) )