В data.table, если хотите:
library(data.table)
DT <- data.table(time = c(0,0,0,1,1,1,2,2,2),
offspring = c('A', 'B', 'C', 'A', 'D', 'E', 'A', 'F', 'G'),
parent = c(NA, NA, NA, 'A', 'B', 'D', 'A', 'A', 'F'))
for (i in seq_len(nrow(DT))) {
DT[i, time := fifelse(time != 0 & offspring %chin% DT[, parent] & !(offspring %chin% DT[seq_len(i-1), offspring]),
time - 0.5,
time)]
}
> DT
time offspring parent
1: 0.0 A <NA>
2: 0.0 B <NA>
3: 0.0 C <NA>
4: 1.0 A A
5: 0.5 D B
6: 1.0 E D
7: 2.0 A A
8: 1.5 F A
9: 2.0 G F
с dplyr:
library(dplyr)
library(tibble)
tbl <- tibble(time = c(0,0,0,1,1,1,2,2,2),
offspring = c('A', 'B', 'C', 'A', 'D', 'E', 'A', 'F', 'G'),
parent = c(NA, NA, NA, 'A', 'B', 'D', 'A', 'A', 'F'))
for (i in seq_len(nrow(tbl))) {
tbl[i,][['time']] <- tbl[i, ] %>% mutate(time = if_else(time != 0 &
offspring %in% tbl[['parent']] &
!(offspring %in% tbl[seq_len(i-1),][['offspring']]),
time - 0.5,
time)) %>% pull(time)
}
> tbl
# A tibble: 9 x 3
time offspring parent
<dbl> <chr> <chr>
1 0 A NA
2 0 B NA
3 0 C NA
4 1 A A
5 0.5 D B
6 1 E D
7 2 A A
8 1.5 F A
9 2 G F