首页 > 解决方案 > 无法将日期从因子更改为日期格式,我不知道为什么

问题描述

我尝试将日期变量从因子格式更改为日期格式,但我不能,也不知道为什么。

这是我的代码

temp_tot <-read.csv("temp_total_030820.csv",header=TRUE,sep=",",na.strings=".", stringsAsFactors=FALSE)
class(temp_tot$date)#character
temp_tot$date<-as.Date(temp_tot$date,format="%m/%d/%y")#returning N.A

这是我的数据的输出

structure(list(X = 1L, capteur = "30-01-s.", Year = 2021L, jj = 1L, 
               variable = "tmax", value = 0.517166666666667, dpt = "Aigoual", 
               pos = "sol", date = "2021-01-01"), row.names = 1L, class = "data.frame")

我已经尝试了很多功能,但我不知道我卡在哪里了。它与“语言环境”有关吗?

谢谢 !

标签: rdateformat

解决方案


在 Value 部分的深处,strptime我们发现If the specified time is invalid (for example ‘&quot;2010-02-30 08:00"’) all the components of the result are ‘NA’.该日期与您的日期相似,我们猜测有效日期(作为输入)将变为 %m%d%Y 或 %d%m%Y:

splits <- strsplit(temp_tot$date, '-')[[1]]
reversed <- rev(splits)
my_valid_date <- as.Date(paste(reversed[1], reversed[2], reversed[3], sep='/'))
class(my_valid_date)
[1] "Date"

我不知道您使用的是欧洲日期格式还是美国日期格式,所以我把它留给您。从 01-01 开始是模棱两可的,并且可能会影响您将颠倒部分放在上面的顺序。高温高压


推荐阅读