Используя dplyr
и tidyr
, я могу создать ожидаемый результат.
library(dplyr)
library(tidyr)
df %>%
mutate(first_tx = ifelse(first_date == dates, txtype, NA)) %>%
fill(first_tx)
ID first_date dates txtype first_tx
1 11 2015-12-23 2015-12-23 A A
2 11 2015-12-23 2016-12-23 A A
3 11 2015-12-23 2017-12-23 B A
4 22 2015-11-01 2015-11-01 B B
5 22 2015-11-01 2016-11-01 C B
6 22 2015-11-01 2016-12-01 C B
data:
df <- structure(list(ID = c(11L, 11L, 11L, 22L, 22L, 22L),
first_date = c("2015-12-23", "2015-12-23", "2015-12-23", "2015-11-01", "2015-11-01", "2015-11-01"),
dates = c("2015-12-23", "2016-12-23", "2017-12-23", "2015-11-01", "2016-11-01", "2016-12-01"),
txtype = c("A", "A", "B", "B", "C", "C")),
.Names = c("ID", "first_date", "dates", "txtype"),
row.names = c(NA, -6L),
class = "data.frame")