Home > Enterprise >  Choose specific levels of a factor variable in R "R version 4.1.2 (2021-11-01)"
Choose specific levels of a factor variable in R "R version 4.1.2 (2021-11-01)"

Time:10-26

I am using ggplot2 to produce plots. The plots have subgroups with different colours. For instance, within ggplot2 I have the following code and the output (hex colour codes) is below it:

levels(df$colour)[1:3]
[1] "#000000" "#bababa" "#e31a1c"

However, I would like to choose levels 1 and 3 and exclude 2 so that the output is "#000000" "#e31a1c".

How do I do this? I tried the below but get TRUE and FALSE rather than the actual Hex codes.

levels(df$colour) %in% c("#000000", "#e31a1c")
 [1] TRUE  FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 
FALSE FALSE FALSE FALSE FALSE FALSE
[21] FALSE FALSE

CodePudding user response:

You can do:

levels(df$colour)[levels(df$colour) %in% c("#000000", "#e31a1c")]

CodePudding user response:

This can be done simply in base r by manually selecting the levels of the factor you want. In your case this would look like this:

levels(df$colour)[c(1,3)]

Which will give you levels 1 and 3.

  • Related