Hello, 

I would like to return a factor from vapply, which looks it cannot be done 
directly since a factor is typeof() numeric. So I’m not sure if the solution 
below is the standard approach to handle this. My concern is that the factor 
levels are mixed up in the results (as shown in the last line of code), which 
is undesirable. 

set.seed(1)
df <- data.frame(x1 = runif(100), x2 = runif(100))


mycuts <- function(x) {
  
  xc <- cut(x, breaks = unique(quantile(x, seq(0, 1, 1/4), na.rm = TRUE)),
            include.lowest = TRUE)
  as.character(xc)
  
}

head(df_out <- data.frame(vapply(df, mycuts, character(nrow(df)))))

identical(levels(df_out$x1), levels(cut(df$x1, breaks = unique(quantile(df$x1, 
                                        seq(0, 1, 1/4), na.rm = TRUE)),
                                        include.lowest = TRUE)))


Thanks for any pointers. 

Axel.
______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to