r - 无法将日期从因子更改为日期格式,我不知道为什么
问题描述
我尝试将日期变量从因子格式更改为日期格式,但我不能,也不知道为什么。
这是我的代码
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")
我已经尝试了很多功能,但我不知道我卡在哪里了。它与“语言环境”有关吗?
谢谢 !
解决方案
在 Value 部分的深处,strptime
我们发现If the specified time is invalid (for example ‘"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 开始是模棱两可的,并且可能会影响您将颠倒部分放在上面的顺序。高温高压
推荐阅读
- ruby-on-rails - 成功上传多个图像和如下格式后,如何从carrierwave获取这些网址?
- git - git-rebase 删除文件,但痕迹保留在 git-rev-list
- python - 将文件输入的行读入Python中的多个列表
- php - 在数据库中找不到记录
- google-apps-script - 有没有可以写在谷歌表格中的脚本,可以“复制到剪贴板”?
- pdf-generation - 在android上打开时生成PDF无效文件格式
- excel - 删除字符串中随机位置的已定义字符
- android - 如何在 Android Studio 中使用我的上传密钥(没有密钥库)签署我的 android 应用程序包?
- python - 使用 Python 按比例计算所有权
- python - CVXPY 对二维数组的约束,同时引用了 3 个元素