gpt4 book ai didi

r - 如果缺少日期值,如何将字符串日期转换为日期类

转载 作者:行者123 更新时间:2023-12-04 06:43:37 24 4
gpt4 key购买 nike

我正在尝试将以下日期转换为 R 中的时间类。出于某种原因,当不包含日期值时,我会返回 NA。如果可能的话,我希望能够按原样处理这个字符向量,而不必粘贴任意的日期值。
谢谢你的帮助。

TS <- c("2004-12", "2005-01", "2005-02", "2005-03", "2005-04", "2005-05", 
"2005-06", "2005-07", "2005-08", "2005-09", "2005-10", "2005-11",
"2005-12", "2006-01", "2006-02", "2006-03", "2006-04", "2006-05",
"2006-06", "2006-07", "2006-08")
TSd <- paste(TS, "01", sep="-")

#doesn't work
as.Date(TS, format="%Y-%m")
as.POSIXlt(TS, format="%Y-%m")

#works
as.Date(TSd, format="%Y-%m-%d")
as.POSIXlt(TSd, format="%Y-%m-%d")

最佳答案

试试 as.yearmon来自 zoo包裹:

library(zoo)
# as.yearmon(TS, "%Y-%m")
as.yearmon(TS)
# [1] "Dec 2004" "Jan 2005" "Feb 2005" "Mar 2005" "Apr 2005" "May 2005" "Jun 2005"
# [8] "Jul 2005" "Aug 2005" "Sep 2005" "Oct 2005" "Nov 2005" "Dec 2005" "Jan 2006"
# [15] "Feb 2006" "Mar 2006" "Apr 2006" "May 2006" "Jun 2006" "Jul 2006" "Aug 2006"

as.Date(as.yearmon(TS))
## [1] "2004-12-01" "2005-01-01" "2005-02-01" "2005-03-01" "2005-04-01"
## [6] "2005-05-01" "2005-06-01" "2005-07-01" "2005-08-01" "2005-09-01"
## [11] "2005-10-01" "2005-11-01" "2005-12-01" "2006-01-01" "2006-02-01"
## [16] "2006-03-01" "2006-04-01" "2006-05-01" "2006-06-01" "2006-07-01"
## [21] "2006-08-01"

format(as.Date(as.yearmon(TS)), "%Y-%m")
## [1] "2004-12" "2005-01" "2005-02" "2005-03" "2005-04" "2005-05" "2005-06"
## [8] "2005-07" "2005-08" "2005-09" "2005-10" "2005-11" "2005-12" "2006-01"
## [15] "2006-02" "2006-03" "2006-04" "2006-05" "2006-06" "2006-07" "2006-08"

关于r - 如果缺少日期值,如何将字符串日期转换为日期类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10446833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com