基于条件的组内日期差异
Date difference within groups based on condition
我有以下数据。 df 是我的起点。 df2是我想要实现的。
df
"ID" "event" "time" "group"
1 FALSE 1990-01-01 1
2 FALSE 1990-01-02 1
3 FALSE 1990-01-03 1
4 TRUE 1990-01-04 1
5 FALSE 1990-01-02 2
6 TRUE 1990-01-03 2
7 FALSE 1990-01-03 3
df2(我需要的)
"ID" "event" "time" "group" distance
1 FALSE 1990-01-01 1 3
2 FALSE 1990-01-02 1 2
3 FALSE 1990-01-03 1 1
4 TRUE 1990-01-04 1 0
5 FALSE 1990-01-02 2 1
6 TRUE 1990-01-03 2 0
7 FALSE 1990-01-03 3 NA
我需要组内任何观察与满足 event=TRUE 条件的观察之间的日期差异(距离列)。如果组中没有事件发生,则应使用 NA 代替距离指示器。
您可以先获取一个数据框,其中仅包含 df
中具有 df$event = TRUE
的那些行。然后将较小的数据框与 df
合并以获得更大的 merged_df
,附加列 merged_df$time.y
告诉您该组最后一次 event=TRUE
出现的日期:
merged_df <- merge(x = df, y = df[df$event == TRUE, ],
by = "group", all.x = TRUE)
df$distance <- ( merged_df$time.y - df$time )
df
# ID event time group distance
#1 1 FALSE 1990-01-01 1 3 days
#2 2 FALSE 1990-01-02 1 2 days
#3 3 FALSE 1990-01-03 1 1 days
#4 4 TRUE 1990-01-04 1 0 days
#5 5 FALSE 1990-01-02 2 1 days
#6 6 TRUE 1990-01-03 2 0 days
#7 7 FALSE 1990-01-03 3 NA days
数据:
df <- structure(list(ID = 1:7, event = c(FALSE, FALSE, FALSE, TRUE,
FALSE, TRUE, FALSE), time = structure(c(7305, 7306, 7307, 7308,
7306, 7307, 7307), class = "Date"), group = c(1L, 1L, 1L, 1L,
2L, 2L, 3L)), .Names = c("ID", "event", "time", "group"), row.names = c(NA,
-7L), class = "data.frame")
我有以下数据。 df 是我的起点。 df2是我想要实现的。
df
"ID" "event" "time" "group"
1 FALSE 1990-01-01 1
2 FALSE 1990-01-02 1
3 FALSE 1990-01-03 1
4 TRUE 1990-01-04 1
5 FALSE 1990-01-02 2
6 TRUE 1990-01-03 2
7 FALSE 1990-01-03 3
df2(我需要的)
"ID" "event" "time" "group" distance
1 FALSE 1990-01-01 1 3
2 FALSE 1990-01-02 1 2
3 FALSE 1990-01-03 1 1
4 TRUE 1990-01-04 1 0
5 FALSE 1990-01-02 2 1
6 TRUE 1990-01-03 2 0
7 FALSE 1990-01-03 3 NA
我需要组内任何观察与满足 event=TRUE 条件的观察之间的日期差异(距离列)。如果组中没有事件发生,则应使用 NA 代替距离指示器。
您可以先获取一个数据框,其中仅包含 df
中具有 df$event = TRUE
的那些行。然后将较小的数据框与 df
合并以获得更大的 merged_df
,附加列 merged_df$time.y
告诉您该组最后一次 event=TRUE
出现的日期:
merged_df <- merge(x = df, y = df[df$event == TRUE, ],
by = "group", all.x = TRUE)
df$distance <- ( merged_df$time.y - df$time )
df
# ID event time group distance
#1 1 FALSE 1990-01-01 1 3 days
#2 2 FALSE 1990-01-02 1 2 days
#3 3 FALSE 1990-01-03 1 1 days
#4 4 TRUE 1990-01-04 1 0 days
#5 5 FALSE 1990-01-02 2 1 days
#6 6 TRUE 1990-01-03 2 0 days
#7 7 FALSE 1990-01-03 3 NA days
数据:
df <- structure(list(ID = 1:7, event = c(FALSE, FALSE, FALSE, TRUE,
FALSE, TRUE, FALSE), time = structure(c(7305, 7306, 7307, 7308,
7306, 7307, 7307), class = "Date"), group = c(1L, 1L, 1L, 1L,
2L, 2L, 3L)), .Names = c("ID", "event", "time", "group"), row.names = c(NA,
-7L), class = "data.frame")