我有一个数据框架,其中包含许多独特的个体在很长一段时间内的生存数据(1 =活着,0 =死亡):每个个体(即每行)都有一系列的0和1(每一列代表一个时间段内的生存判断).我现在想判断每个人的时间序列的逻辑,即逻辑将是如果一个人一直活着,或者如果它在途中死亡并保持死亡.不合逻辑的是,如果一个人死了,但在以后的时间点又活了,即它复活了.我想在我的数据框中添加一个新列,显示个人的时间序列是"好"还是"不好".
我可以用dplyr::case_when()
来说明所有的可能性,但由于我的时间序列很长,这实际上是不可行的.
有没有一种巧妙的方法(理想情况下使用dplyr,但一切都很好)来测试这种时间序列的逻辑?
请注意,情况并非如此.
# A tibble: 6 × 7
ind_ID timeperiod_1 timeperiod_2 timeperiod_3 timeperiod_4 timeperiod_5 logic_status
<chr> <fct> <fct> <fct> <fct> <fct> <chr>
1 ID_1 1 1 1 1 1 ok
2 ID_2 1 0 1 0 0 not ok
3 ID_3 1 1 1 1 1 ok
4 ID_4 1 1 1 0 0 ok
5 ID_5 1 0 1 0 0 not ok
6 ID_6 1 0 1 0 0 not ok
示例数据:
dput(dat)
structure(list(ind_ID = c("ID_1", "ID_2", "ID_3", "ID_4", "ID_5",
"ID_6"), timeperiod_1 = structure(c(2L, 2L, 2L, 2L, 2L, 2L), levels = c("0",
"1"), class = "factor"), timeperiod_2 = structure(c(2L, 1L, 2L,
2L, 1L, 1L), levels = c("0", "1"), class = "factor"), timeperiod_3 = structure(c(2L,
2L, 2L, 2L, 2L, 2L), levels = c("0", "1"), class = "factor"),
timeperiod_4 = structure(c(2L, 1L, 2L, 1L, 1L, 1L), levels = c("0",
"1"), class = "factor"), timeperiod_5 = structure(c(2L, 1L,
2L, 1L, 1L, 1L), levels = c("0", "1"), class = "factor")), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))