[R] Returning a factor from vapply

Axel Urbiz axel.urbiz at gmail.com
Wed Nov 25 12:49:24 CET 2015


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.


More information about the R-help mailing list