Why use as.factor() instead of just factor()

as.factor is a wrapper for factor, but it allows quick return if the input vector is already a factor: function (x) { if (is.factor(x)) x else if (!is.object(x) && is.integer(x)) { levels <- sort(unique.default(x)) f <- match(x, levels) levels(f) <- as.character(levels) if (!is.null(nx <- names(x))) names(f) <- nx class(f) <- “factor” f } else factor(x) … Read more

Concatenate rows of a data frame

While others have focused on why your code isn’t working and how to improve it, I’m going to try and focus more on getting the result you want. From your description, it seems you can readily achieve what you want using paste: df <- data.frame(letters = LETTERS[1:5], numbers = 1:5, stringsAsFactors=FALSE) paste(df$letters, df$numbers, sep=””)) ## … Read more

Create frequency tables for multiple factor columns in R

You were nearly there. Just one small change in your function would have got you there. The x in function(x) … needs to be passed through to the table() call: levs <- c(“Not Impt at all”, “Somewhat Impt”, “Neutral”, “Impt”, “Very Impt”) sapply(x.sample, function(x) table(factor(x, levels=levs, ordered=TRUE))) A little re-jig of the code might make … Read more

Idiom for ifelse-style recoding for multiple categories

You could convert your variable to a factor and change its levels by levels<- function. In one command it could be like: `levels<-`( factor(dat$product), list(Tylenol=1:3, Advil=4:6, Bayer=7:9, Generic=10:12) ) In steps: brands <- factor(dat$product) levels(brands) <- list(Tylenol=1:3, Advil=4:6, Bayer=7:9, Generic=10:12)

How to change order of boxplots when using ggplot2?

Have you tried this: df2$variable <- factor(df2$variable, levels = c(‘vph.shr’,’vnu.shr’),ordered = TRUE) I just picked an ordering there, since my system is configured slightly differently than yours I suspect, so my ‘default ordering’ may differ. But you can just switch the position of levels when specifying them. A few other options, depend on your tastes: … Read more