不带as.Date的字符串20130118的日期转换 [英] Date conversion of string 20130118 with as.Date not succeeding

查看:45
本文介绍了不带as.Date的字符串20130118的日期转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组日期,格式如下:

I have a set of dates formatted as following:

datevalue <- 20130118

我想将它们格式化为正确的日期,然后尝试使用以下代码进行操作:

I want to format them to a proper date and I try to do this with the following code:

date <- as.Date(datevalue,"%Y%m%d")

这与文档中列出的示例非常相似,但由于某些原因无法正常工作。在文档中列出了以下示例:

This is very similar to the example listed in the documentation but for some reason not working. In the documentation the following example is listed:

dates <- c("02/27/92", "02/27/92", "01/14/92", "02/28/92", "02/01/92")
as.Date(dates, "%m/%d/%y")
[1] "1992-02-27" "1992-02-27" "1992-01-14" "1992-02-28"
[5] "1992-02-01"

但是,我收到以下错误消息: charToDate(x)中的错误:字符串不在标准明确格式。从某种程度上来说,这对我来说很有意义,但是我感觉我的语法正确地定义了它。谁能解释为什么代码不起作用?

However, I get the following error message: "Error in charToDate(x): character string is not in a standard unambiguous format". This makes at some level sense to me, but I have the feeling that my syntax defined it properly. Anybody who can explain why the code is not working?

推荐答案

将变量定义为字符(如@Arun的评论中所述)工作了。代码:

Defining the variable as a character (as mentioned in @Arun's comment) worked. Code:

date2 <- as.Date(as.character(datevalue),"%Y%m%d")

这篇关于不带as.Date的字符串20130118的日期转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆