将年月格式设置为POSIXct [英] format year-month to POSIXct

查看:139
本文介绍了将年月格式设置为POSIXct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些年份格式的数据,我想将这些数据格式化为 ggplot

I have some data in year-month form that I want to format for graphing in ggplot.

date <- c("2016-03", "2016-04", "2016-05", "2016-06", "2016-07", "2016-08", 
"2016-09", "2016-10", "2016-11", "2016-12")

我使用的是 parsedate :: parse_date ,但是由于更新了R,它不再起作用。

I was using parsedate::parse_date, but since updating R it no longer functioning.

我看过

在R

as.yearmon 中设置日期格式(年月)可以正常工作,但它不会格式化为 ggplot 所需的POSIXct。其他格式,例如 as.POSIXct strptime 给出NA或错误。

as.yearmon works fine but it doesn't format to POSIXct which I need for ggplot. Other formatting such as as.POSIXct and strptime are giving NAs or errors.

注意:我不介意每月的第一天是否添加为 year-mo格式。

Note: I don't mind if the first of the month gets added to the "year-mo" format.

推荐答案

这是一个常见问题解答:日期由日期,月份和年份组成。您缺少一部分。因此,通过添加 a 天,例如 -01,您可以添加缺少的字符串结构并进行解析。或者,您可以使用更宽容的解析器:

That's a FAQ: a date is comprised of day, month and year. You are missing one part. So by adding a day, say, '-01', you can impose the missing string structure and parse. Or you can use a more tolerant parser:

R> library(anytime)
R> anydate("2017-06")
[1] "2017-06-01"
R> 

哪个也可以为您的数据服务:

Which works for your data too:

R> date
 [1] "2016-03" "2016-04" "2016-05" "2016-06"
 [5] "2016-07" "2016-08" "2016-09" "2016-10"
 [9] "2016-11" "2016-12"
R> anydate(date)
 [1] "2016-03-01" "2016-04-01" "2016-05-01"
 [4] "2016-06-01" "2016-07-01" "2016-08-01"
 [7] "2016-09-01" "2016-10-01" "2016-11-01"
[10] "2016-12-01"
R> 

最后,您对 POSIXct 类型的请求仍然很短第二。但是按照相同的原则:

Lastly, your request for POSIXct type is still short an hour, minute and second. But by the same principle:

R> anytime(date)
 [1] "2016-03-01 CST" "2016-04-01 CDT"
 [3] "2016-05-01 CDT" "2016-06-01 CDT"
 [5] "2016-07-01 CDT" "2016-08-01 CDT"
 [7] "2016-09-01 CDT" "2016-10-01 CDT"
 [9] "2016-11-01 CDT" "2016-12-01 CST"
R> 

这两个函数返回正确的 Date POSIXct 类型。

These two functions return proper Date and POSIXct types, respectively.

这篇关于将年月格式设置为POSIXct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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