Вот как бы я сделал это с Tidyverse
library(tidyverse)
# create data
df_raw <- data.frame(ID = c(1:4),
Start_year = c(2005,2006,2007,2006),
Status_2005 =c("GBR", NA, NA, NA),
Status_2006 =c("GBR", "FRA", NA, "UKR"),
Status_2007 =c("FRA", "FRA", "GBR", "RUS"),
stringsAsFactors = F)
df <- df_raw %>%
gather(starts_with("Status"), key = Key, value = Value ) %>%
arrange(ID) %>%
drop_na(Value) %>%
mutate(cnt = unlist(map(rle(ID)$lengths-1, seq, from = 0, by =1 ))) %>%
mutate(Key = paste0("Year_", cnt)) %>%
select(-Start_year, -cnt) %>%
spread(key = Key, value = Value)
df
#> ID Year_0 Year_1 Year_2
#> 1 1 GBR GBR FRA
#> 2 2 FRA FRA <NA>
#> 3 3 GBR <NA> <NA>
#> 4 4 UKR RUS <NA>