错误:无效输入:date_trans 仅适用于 Date 类的对象 // 不知道如何解决

问题描述

我不断收到以下错误,无法弄清楚出了什么问题。请帮忙!

错误:无效输入:date_trans 仅适用于 Date 类的对象

我的代码如下。

#Problem 3b: Plot a line graph of the average monthly consumption in this population,with months on the x-axis running from January to December (1-12) and the consumption on the y axis.

rm(list=ls())
library(tidyverse)

# Read the discom_data.csv
discom_linegraph=read_csv("/Users/morgandenlow/Desktop/data_files/discom_data.csv")

#Aggregate consumption for each household annually for each year
electricity.utility.month = discom_linegraph %>% group_by(month) %>% summarise(monthly_consumption = mean(unitsconsumed,na.rm=TRUE))

electricity.utility.month$month = as.factor(electricity.utility.month$month)

data <- data.frame(electricity.utility.month$month)

#new date variable
electricity.utility.month$month <- as.Date(paste(electricity.utility.month$month,1,sep="-"),format="%Y-%W-%w")


ggplot(data,aes(x = electricity.utility.month$month,y = electricity.utility.month$unitsconsumed)) 
+geom_line(color = "blue4") 
+ scale_x_date(date_breaks = "1 month",date_labels = "%b\n%Y") 
+scale_y_continuous(labels = NULL,limits = c(0,100)) 
+labs(x = "Month",y = "Average consumption (kWh)",title = "Average consumption by month") 
+theme_bw() 
+theme(panel.grid.minor = element_blank(),panel.grid.major.x = element_blank(),plot.title = element_text(size = 14,face = "bold",hjust = 0.5))

解决方法

我没有数据,但您可以尝试,不要将 month 转换为 factor

electricity.utility.month$month = as.factor(electricity.utility.month$month)

跳过这一行。