year_cols: Find year columns

View source: R/utilities.R

year_colsR Documentation

Find year columns

Description

It is sometimes helpful to know which columns are years. This function returns a set of indices (or, optionally, the names) of columns in .df that represent years.

Usage

year_cols(
  .df,
  year_pattern = "^-?\\d+$",
  year = IEATools::iea_cols$year,
  return_names = FALSE
)

Arguments

.df

A data frame with years spread to the right in columns.

year_pattern

A regex pattern that identifies years. Default is "⁠^-?\\d+$⁠".

year

See IEATools::iea_cols$year.

return_names

A boolean which tells whether names are returned instead of column indices. Default is FALSE.

Details

The default year_pattern is "⁠^-?\\d+$⁠", which matches columns whose names have zero or one negative signs followed by any number of digits.

If .df is tidy, it may have a "Year" column which is included in the return value. To disable this behavior, set year = NULL.

Value

a vector of column indices (when return_names = FALSE, the default) or a vector of column names (when return_names = TRUE) for those columns that represent years.

Examples

DF <- data.frame(a = c(1, 2), `1967` = c(3, 4), `-42` = c(5, 6), check.names = FALSE)
DF %>% year_cols()
DF %>% year_cols(return_names = TRUE)
DF2 <- data.frame(data.frame(a = c(1, 2), Year = c(1967, 2020)))
DF2 %>% year_cols(return_names = TRUE)

MatthewHeun/IEATools documentation built on Feb. 6, 2024, 3:29 p.m.