问题
This question already has an answer here:
- Drop factor levels in a subsetted data frame 14 answers
I have the following code:
x = rnorm(30, 1, 1)
c = c(rep("x1",10), rep("x2",10), rep("x3",10))
df = dataframe(x,c)
boxplot(x ~ c, data=df)
It works great. But if I decide I am no longer interested in seeing x3, remove it, and replot:
dfMod = subset(df, c %in% c("x1", "x2"))
boxplot(x ~ c,data=dfMod)
The boxplot still shows a column for x3.
Ive tried giving boxplot a hint using
boxplot(x~c,data=dfMod, names = c("x1", "x2"))
but this throws the error that names size is not right. Thanks in advance for the help
回答1:
Use droplevels after subset
dfMod <- subset(df, c %in% c("x1", "x2"))
dfMod$c <- droplevels(dfMod$c)
boxplot(x ~ c,data=dfMod)
You can also use class to change factor to character and subsetting inside boxplot call
class(df) <- c("numeric", "character")
boxplot(x ~ c, subset=c %in% c("x1", "x2"), data=df)
来源:https://stackoverflow.com/questions/19965333/remove-unused-categorical-values-boxplot-r