3

I recently upgraded to R Studio Version 1.1.463. However, I am having issues with several ggplots related to factors. Here is one of the cases where I get the error:

I have a data frame (df) with 3 variables:

  • Name (factor, with 3 levels)
  • Type (factor, with 35 levels)
  • Group (factor, with 6 levels)

When I want to arrange a Data Frame (df) by levels of a factor, as follows

df$Type <- factor(df$Type, levels = df$Type[order(df$Group)])

in order to plot a geom_tile as in this example:

print(ggplot(df, aes(x = factor(Name), y = Type, fill = Group)) +
    geom_tile()

I get the following error:

"Error in `levels<-`(`*tmp*`, value = as.character(levels)) : factor level [2] is duplicated"

I have checked the factors for all three variables, using

levels(df$Name)
levels(df$Group)
levels(df$Type)

and they are not duplicated. If I don't run the first line of code mentioned in this example, the plot is produced, but not in the order I want (I want all Types of the same Group to be placed close together).

If I run the graph on R Studio Version 1.0.136, it works fine.

I appreciate any clue as to what could be going on.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
Juliana Gómez
  • 301
  • 1
  • 3
  • 10
  • 3
    I doubt this is an rstudio thing, it's almost certainly `ggplot2` or R related, unless you can prove that identical versions of R and `ggplot2` have this behavior in different versions of RStudio (which I find hard to believe). – r2evans Nov 07 '18 at 18:00
  • 10
    The complaint is about duplicates in the `levels` argument. Make it `levels = unique(df$Type[order(df$Group)])` – Gregor Thomas Nov 07 '18 at 18:00
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Nov 07 '18 at 18:02
  • 3
    Removing `RStudio` and `ggplot2` flags. The R version might make a difference, but the RStudion version won't. And it's inconsequential that these factors are used in a `ggplot`. – Gregor Thomas Nov 07 '18 at 18:02
  • 1
    Your error is here: `levels = df$Type[order(df$Group)])` . You have 35 levels for Type and you are trying to order with 6 values from Group, of course you are getting multiple values. With any sample data or a clear definition of your expected results, it is impossible to provide a complete answer. – Dave2e Nov 07 '18 at 19:50

0 Answers0