I left out the example:
> set.seed(1)
> df <- data.frame(x1 = rpois(1000,4), x2 = rpois(1000,8))
> helper_fun <- function(x) {
+ cut(x, breaks = unique(quantile(x, seq(0, 1, 1/10), na.rm = TRUE)),
+ include.lowest = TRUE)
+ }
> df2 <- data.frame(lapply(df, helper_fun))
> lapply(df
Here's a solution with dplyr
my_cut <- function(x){
breaks <- quantile(x, seq(0, 1, by = 0.1))
y <- cut(x, breaks = breaks, include.lowest = TRUE)
levels(y) <- paste(head(letters, length(breaks) - 1), levels(y), sep = ":
")
return(y)
}
library(dplyr)
mutate_each(df, funs = funs(my_cut))
Don't use vapply() here - use lapply() instead and then leave cut's output
alone.
vapply() will combine its outputs to create a character matrix and
data.frame will pull apart the character matrix into its columns. Skipping
the matrix intermediary solves
lots of issues.
Bill Dunlap
TIBCO Softwar
Dear list,
What is a better way relative to the one below to keep the order of factor
levels created from cut()? Notice, I'm simply pasting letters to levels before
converting to character so to keep the desired order of levels. This is not
very elegant... I'm converting to character so I can c
4 matches
Mail list logo