Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider adding helper functions when creating composition data #152

Open
chantelwetzel-noaa opened this issue Sep 23, 2024 · 0 comments
Open

Comments

@chantelwetzel-noaa
Copy link
Contributor

Incorporating helper functions could streamline the code and reduce code redundancy within and across functions. Below are some example helper functions that could be considered:

# Two helper functions
make_long_comp <- function(data) {
  data |>
    dplyr::group_by(year, full_bin, sex) |>
    dplyr::summarize(
      expansion = sum(expansion)
    ) |>
    dplyr::group_by(year) |>
    dplyr::mutate(proportion = prop.table(expansion)) |>
    dplyr::select(-expansion)
}
pivot_wider_comp <- function(data) {
  data_long <- data |>
    tidyr::separate(full_bin, into = c("bin", "group")) |>
    dplyr::mutate(
      bin_factor = forcats::fct_cross(
        forcats::as_factor(as.numeric(bin)),
        forcats::as_factor(sex)
      )
    )
  temporary_levels <- levels(data_long[["bin_factor"]])
  data_wide <- data_long |>
    tidyr::pivot_wider(
      id_cols = year,
      names_from = bin_factor,
      values_from = proportion
    ) |>
    dplyr::select(year, temporary_levels)
  return(data_wide)
}
# Using the helper functions to create a list of length 3, basically one list with each of the output types for SS3, this would replace quite a bit of code that starts with the creation of `total_by_year`
attempt <- stratum_exp |>
  tidyr::pivot_longer(
    cols = c(-year, -strata, -bin),
    names_to = "sex",
    values_to = "expansion"
  ) |>
  dplyr::mutate(
    sex_group = ifelse(sex %in% c("female", "male"), "sexed", sex),
    full_bin = paste(bin, sex_group, sep = ":")
  ) |>
  dplyr::group_by(sex_group) |>
  dplyr::group_split() |>
  purrr::map(make_long_comp) |>
  purrr::map(pivot_wider_comp)

However, there are a few issues that would need to be sorted through prior to implementation:

  1. Using an external vector in selections was deprecated in tidyselect 1.1.0. Please use all_of() or any_of() instead.
  2. NaN and NA created need to be replaced with 0.
  3. The composition data are not output in the order of the composition bin and would need to be reordered.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant