-
Notifications
You must be signed in to change notification settings - Fork 23
Open
Description
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)
}Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels