簡體   English   中英

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() (而不是 max),但例如,如果一個人結婚 2 年,離婚,然后結婚 6 年,我將無法在這個新變量中看到她結婚 6 年,如果我不添加條件>=5

有沒有人有一個可以幫助我的代碼的想法?

我不完全確定您期望的 output 試圖代表什么。 如果您希望每個vn的第一次婚姻的長度 >=5 年,您可以使用

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

也許這太令人費解但似乎有效:

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 時首次給出索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM