【问题标题】:Why the error "factor level [2] is duplicated" will occur?为什么会出现“因子级别[2]重复”的错误?
【发布时间】:2021-02-28 08:28:00
【问题描述】:
我尝试使用因子(月)将月份变量(整数)转换为分类变量,但由于错误而失败。我该如何解决?
这是我的代码:
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()
【问题讨论】:
标签:
r
factors
data-transform
【解决方案1】:
您的分配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()