R中使用as.Date至今的字符,但给出的答案是一次又一次的相同日期

问题描述

我正在尝试将名为Date18的列从字符转换为日期,但是使用功能as.Date()可以得到的答案却大不相同。另外,我有大量的值样本。

str(coo)
'data.frame':   7698 obs. of  2 variables:

 $ Date18: chr  "1/3/2018 9:06" "1/3/2018 10:14" "1/3/2018 10:19" "1/3/2018 10:30" ...

 $ Amount: num  21 16.8 10.5 43.7 4.2 ...

coo$Date18=as.Date(coo$Date18)

str(coo)

'data.frame':   7698 obs. of  2 variables:

 $ Date18: Date,format: "0001-03-20" "0001-03-20" ...

 $ Amount: num  21 16.8 10.5 43.7 4.2 ...

您可以看到日期格式已更改。如何转换日期,但我的值不会改变?

解决方法

对于as.Date,如果不是默认格式(format),我们需要指定"%Y-%m-%d"

as.Date(coo$Date18,"%m/%d/%Y %H:%M")

注意:在这里似乎是月份然后是月份。如果是天然后是月,请使用as.Date(coo$Date18,"%d/%m/%Y %H:%M")。此外,请记住,如果年份是四个数字(例如,年份),则Y必须大写。如果年份是两个数字,则为2001年和小写字母,例如01。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...