levels
Why is the terminology of labels and levels in factors so weird?
I think the way to think about the difference between labels and levels (ignoring the labels() function that Tommy describes in his answer) is that levels is intended to tell R which values to look for in the input (x) and what order to use in the levels of the resulting factor object, and labels … Read more
ggplot2 keep unused levels barplot
You need to set drop=FALSE on both scales (fill and x) like this: library(ggplot2) df <- data.frame(type=c(“A”, “A”, “A”, “B”, “B”), group=rep(“group1”, 5)) df1 <- data.frame(type=c(“A”, “A”, “A”, “B”, “B”, “A”, “A”, “C”, “B”, “B”), group=c(rep(“group1”, 5),rep(“group2”, 5))) df$type <- factor(df$type, levels=c(“A”,”B”, “C”)) df1$type <- factor(df1$type, levels=c(“A”,”B”, “C”)) plt <- ggplot(df, aes(x=type, fill=type)) + geom_bar(position=’dodge’) … Read more
Re-ordering factor levels in data frame [duplicate]
Assuming your dataframe is mydf: mydf$task <- factor(mydf$task, levels = c(“up”, “down”, “left”, “right”, “front”, “back”))
`levels
The answers here are good, but they are missing an important point. Let me try and describe it. R is a functional language and does not like to mutate its objects. But it does allow assignment statements, using replacement functions: levels(x) <- y is equivalent to x <- `levels<-`(x, y) The trick is, this rewriting … Read more
Reorder levels of a factor without changing order of values
Use the levels argument of factor: df <- data.frame(f = 1:4, g = letters[1:4]) df # f g # 1 1 a # 2 2 b # 3 3 c # 4 4 d levels(df$g) # [1] “a” “b” “c” “d” df$g <- factor(df$g, levels = letters[4:1]) # levels(df$g) # [1] “d” “c” “b” “a” … Read more