You can create an ID for the continuous periods:
dat$cont_per <- cumsum(!c(TRUE, diff(dat$Year)==1))
And then compute the min/max values based on that. For example, with data.table:
library(data.table)
setDT(dat)
dat[, Period := paste(min(Year), max(Year), sep="-"), by=cont_per]
dat
# Year Val cont_per Period
# 1: 1950 1 0 1950-1955
# 2: 1951 2 0 1950-1955
# 3: 1952 3 0 1950-1955
# 4: 1953 4 0 1950-1955
# 5: 1954 5 0 1950-1955
# 6: 1955 6 0 1950-1955
# 7: 1957 7 1 1957-1960
# 8: 1958 8 1 1957-1960
# 9: 1959 9 1 1957-1960
# 10: 1960 10 1 1957-1960
# 11: 1965 11 2 1965-1970
# 12: 1966 12 2 1965-1970
# 13: 1967 13 2 1965-1970
# 14: 1968 14 2 1965-1970
# 15: 1969 15 2 1965-1970
# 16: 1970 16 2 1965-1970
N.B.: You can also compute the Period
directly, without creating the variabel cont_per
:
setDT(dat)[, Period := paste(min(Year), max(Year), sep="-"), by=cumsum(!c(TRUE, diff(Year)==1))]
head(dat)
# Year Val Period
# 1: 1950 1 1950-1955
# 2: 1951 2 1950-1955
# 3: 1952 3 1950-1955
# 4: 1953 4 1950-1955
# 5: 1954 5 1950-1955
# 6: 1955 6 1950-1955
Similarly, with dplyr:
dat %>%
group_by(count_per=cumsum(!c(TRUE, diff(dat$Year)==1))) %>%
mutate(Period=paste(min(Year), max(Year), sep="-"))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…