R语言笔记 日期值
更新:HHH   时间:2023-1-7


日期值通常以字符串的形式输入到R中,然后转化为以数值形式存储的日期变量。函数

as.Date()用于执行这种转化。其语法为as.Date(x, "input_format"),其中x是字符型数

据,input_format则给出了用于读入日期的适当格式

符 号 含 义 示 例

%d 数字表示的日期(0~31) 01~31

%a 缩写的星期名 Mon

%A 非缩写星期名 Monday

%m 月份(00~12) 00~12

%b 缩写的月份 Jan

%B 非缩写月份 January

%y 两位数的年份 07

%Y 四位数的年份 2007


> mydate <- as.Date(c("2017-09-01","2008-08-08"))

> mydate

[1] "2017-09-01" "2008-08-08"

> dates <- as.Date("05/01/2014","%m/%d/%Y")

> dates

[1] "2014-05-01"


> Sys.Date()

[1] "2016-04-04"

> date()

[1] "Mon Apr 04 13:07:07 2016"



你可以使用函数format(x, format="output_format")来输出指定格式的日期值,并且

可以提取日期值中的某些部分:

> today <- Sys.Date()

> format(today,"%B")

> format(today,"%B %d %Y")

[1] "四月 04 2016"


------------日期计算

> startdate <- as.Date("1988-12-16")

> nowdate <- Sys.Date()

> nowdate-startdate

Time difference of 9971 days


> difftime(today,startdate,units="weeks")

Time difference of 1424.429 weeks

你同样可以将日期变量转换为字符型变量——虽然不太常用。函数as.character()可将日

期值转换为字符型:


返回编程语言教程...