r - 在 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
. 有人可以指导我如何完成这个吗?
解决方案
你应该使用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"
推荐阅读
- c++ - 选择某些项目时,MFC如何在组合框中键入
- mysql - MySQL加入分组没有完美加入
- javascript - 如何在我的 src 文件夹中不包含 mocha (TDD) 函数,如“describe”和“it”,而只包含在 test 文件夹中?[TS]
- java - Spring Cloud Gateway:在自定义谓词中设置响应状态码
- ggplot2 - 什么是 Julia 的 R 等效 ggplot 代码?
- postgresql - 如何在 postgres 中检索表空间的状态
- python - 编译的 Python 脚本无法运行用户在 Windows cmd 中给它的命令
- font-awesome - 字体真棒样式的问题是什么?
- javascript - 单击滑块中的项目时内容不更改(javascript 和 php)
- c# - C# 字符串在分隔符之间拆分