简体   繁体   中英

Why the error “factor level [2] is duplicated” will occur?

I tried to convert the month variable (which is an integer) into a categorical variable using factor(month), but I failed because of the error. How could I solve it?

This is my code:

library(tidyverse)
library(dplyr)
install.packages("nycflights13")
library(nycflights13)
month_new <- flights$month
month_new
flights %>%
   filter(dest == "HNL", air_time > 10) %>%
   factor(month_new) %>%
   ggplot(x = month_new) + geom_bar()

Your assignment factor(month_new) does not work. I suggest mutate(month = as.factor(month)) and there is no aesthetics aes

library(tidyverse)
#install.packages("nycflights13")
library(nycflights13)

  flights %>%
    filter(dest == "HNL", air_time > 10) %>%
    mutate(month = as.factor(month)) %>%
    ggplot(aes(x = month)) + 
    geom_bar()

or:

library(tidyverse)
#install.packages("nycflights13")
library(nycflights13)

flights %>%
  filter(dest == "HNL", air_time > 10) 

  ggplot(flights, aes(x=factor(month)))+
    geom_bar(fill="steelblue")+
    theme_minimal()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM