首页 > 解决方案 > 为什么会出现“因子级别[2]重复”的错误?

问题描述

我尝试使用因子(月)将月份变量(整数)转换为分类变量,但由于错误而失败。我该如何解决?

这是我的代码:

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()

标签: rfactorsdata-transform

解决方案


你的任务factor(month_new)不起作用。我建议mutate(month = as.factor(month))并且没有美学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()

或者:

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()

推荐阅读