R/with_min_yrs.R

Defines functions with_min_yrs

Documented in with_min_yrs

#' Select Countries with Observations in a Minimum Number of Distinct Years
#'
#' \code{with_min_yrs} is a convenience function for filtering data to be input to \code{dcpo} by the number of country-years observed
#'
#' @param x a data frame of survey items and marginals generated by \code{dcpo_setup}
#' @param min_yrs the minimum number of distinct years needed for a country included in x to be retained
#'
#' @return a data frame
#'
#' @importFrom dplyr "%>%" filter mutate group_by ungroup
#'

#' @export
with_min_yrs <- function(x, min_yrs) {
  if (!is.na(min_yrs)) {
    country <- yr_obs <- NULL

    x <- x %>%
      group_by(country) %>%
      mutate(yr_obs = length(unique(year))) %>%
      filter(yr_obs >= min_yrs) %>%
      select(-yr_obs) %>%
      ungroup()
  }
  return(x)
}
fsolt/DCPOtools documentation built on June 9, 2025, 4:10 p.m.