[R] Returning a factor from vapply

Jeff Newmiller jdnewmil at dcn.davis.ca.us
Wed Nov 25 15:15:39 CET 2015

Such manipulations are usually better performed in character data.  Convert to factor only after the vector is complete. 
Sent from my phone. Please excuse my brevity.

On November 25, 2015 3:49:24 AM PST, Axel Urbiz <axel.urbiz at gmail.com> wrote:
>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. 
>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 =
>            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 =
>                                        seq(0, 1, 1/4), na.rm = TRUE)),
>                                        include.lowest = TRUE)))
>Thanks for any pointers. 
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>PLEASE do read the posting guide
>and provide commented, minimal, self-contained, reproducible code.

	[[alternative HTML version deleted]]

More information about the R-help mailing list