Skip to content

Add quantile with rename function #137

@karissawhiting

Description

@karissawhiting
add_ntile <- function(df, percentile, variable) {
  # Determine the number of tiles based on the percentile type
  ntiles <- switch(
    percentile,
    "median" = 2,
    "tertile" = 3,
    "quantile" = 4,
    stop("Choose 'median', 'tertile', or 'quantile'")
  )
  
  # Compute quantile breaks for the variable
  breaks <- quantile(df[[variable]],
                     probs = seq(0, 1, length.out = ntiles + 1),
                     na.rm = TRUE)
  
  # Cut the variable into the specified percentiles
  percentiles <- cut(df[[variable]], breaks = breaks, include.lowest = TRUE)
  
  # Rename the levels
  new_levels <- glue::glue("{percentile} {1:ntiles}: {levels(percentiles)}")
  levels(percentiles) <- new_levels
  
  # Add the new percentile column to the data frame
  var_name_to_add <- 
    as.character(glue::glue("{variable}_{percentile}"))

  df <- df %>%
    mutate(!!var_name_to_add := percentiles)

  return(df)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions