我有一个字符串列出了一个人的任期,例如.
all_terms <- "2012 to 2024, 2007 to 2007, 2001 to 2003, 2000 to 2009, 2010 to 2011"
我想知道这个人是否连续任职,这意味着:
-
一个任期的结束年份和另一个任期的开始年份可以相差1,即2011年结束的任期和2012年开始的新任期将被视为连续的.
-
在其他任期内或跨越其他任期的任期不应影响连续性,即上文2001年至2003年的任期属于2000年至2009年,不影响连续性.同样,2008年至2013年的任期不会影响连续性.
因此,上述例子将被认为是连续的,但这个-"1989年到2008年,2020年到2024年"将不是.
我想出了这个代码,但它不工作:
all_terms <- "2012 to 2024, 2007 to 2007, 2001 to 2003, 2000 to 2009, 2010 to 2011"
# Process terms to extract years and create a data frame
terms_list <- str_split(all_terms, ",\\s*")[[1]]
years <- map(terms_list, ~str_extract_all(.x, "\\d{4}")[[1]])
years_df <- map_df(years, ~data.frame(start = as.numeric(.x[1]), end = as.numeric(.x[2])))
# Sort years by start date
years_df <- years_df %>% arrange(start)
# Adjust end year by adding one for continuity check
years_df$modified_end <- years_df$end + 1
# Check for continuity
is_continuous <- all(c(TRUE, tail(years_df$start, -1) <= head(years_df$modified_end, -1)))
# Results
list(
is_continuous = is_continuous,
start_years = min(years_df$start),
end_years = max(years_df$end)
)