首页 > 解决方案 > 在 R 中处理日期转换

问题描述

我手动创建了一列日期。需要将整列 Date 转换为 xx/xx/xxxx (01/dd/2012) 我知道如何使用子字符串从 01JAN12 等标准数据类中提取月日年

DateM=substr(Date,START,FINISH)
DateM
Now put it together as xx/xx/xx

这是我的代码:

Date=c("January 23,2012","January 24,2012","January 
        25,2012","January 26,2012","January 27,2012")

# WANT: 23JAN12  24JAN12  25JAN12  26JAN12  27JAN12
Date3=format(Date,"%B %d %Y") 
# Error in format.default(Date, "%B %d %Y") : invalid 'trim' 
  argument but I still get the dates ok when I print out

#WANT: 01/23/2012 01/24/2012 01/25/2012 01/26/2012 01/27/2012 from 
       Date3
Date4=format(Date3,"%B  %d  %Y")  
invalid 'trim' argument

# WANT: 2012-01-23 2012-01-24 2012-01-25 2012-01-26 2012-01-27
Date5=format(Date3,"%Y %B  %d")  
invalid 'trim' argument      

我想使用 R 的基本功能,而不是lubridate. 有人可以指导我如何完成这个吗?

标签: r

解决方案


你应该使用as.Date而不是format

as.Date(Date, "%B %d, %Y")
#[1] "2012-01-23" "2012-01-24" "2012-01-25" "2012-01-26" "2012-01-27"

as.Date用于将日期从不同的字符表示形式转换为"Date"类。

一旦你在"Date"类中有数据,我们就可以用format我们想要的方式来表示它们。

format(as.Date(Date, "%B %d, %Y"), "%m/%d/%Y")
#[1] "01/23/2012" "01/24/2012" "01/25/2012" "01/26/2012" "01/27/2012"

推荐阅读