Remove Unused categorical values boxplot - R [duplicate]

大憨熊 提交于 2019-11-27 04:49:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!