Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

r - How to convert a character string date to date class if day value is missing

I'm trying to convert the following dates to a time class in R. For some reason, I am getting NAs returned when a day value is not included. I would like to be able to handle this character vector as is without having to paste an arbitrary day value if possible. Thanks for your help.

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")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try as.yearmon from the zoo package:

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...