Skip to content

Instantly share code, notes, and snippets.

@danlewer
Last active March 17, 2019 13:43
Show Gist options
  • Save danlewer/806c0d003fdb6e716b29bdfa0dd16d2a to your computer and use it in GitHub Desktop.
Save danlewer/806c0d003fdb6e716b29bdfa0dd16d2a to your computer and use it in GitHub Desktop.
Turn a continuous variable into a labelled factor variable (wrapper for findInterval)
make_age_group <- function(ages, min_val = seq(10, 100, 10)) {
x <- findInterval(ages, min_val)
y <- setNames(as.data.frame.list(aggregate(ages, list(x), range)), c('group', 'min', 'max'))
y$label <- ifelse(y$min == y$max, y$min, paste0(y$min,'-',y$max))
return(factor(x, y$group, y$label))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment