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
407 views
in Technique[技术] by (71.8m points)

r - Parse string with additional characters in format to Date

I have a string variable that I want to parse to class Date. In addition to the day, year and month, the format has other characters like separators (, ), letters and apostrophes (u''), like this:

"u'9', u'2005', u'06'"

I have tried

as.Date(my_data$date, format = '%d %Y %m')

...but it only produces missing values. I was hoping that R would interpret the u'' as a unicode designator, which it doesn't.

How do I strip all those unused characters so that this "u'9', u'2005', u'06'" becomes simply this "9 2005 06"?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You don't need to strip the characters not used in the conversion specification. In ?as.Date, the format argument is pointing to ?strptime ("Otherwise, the processing is via strptime"). In the Details section of ?strptime* we find that:

"[a]ny character in the format string not part of a conversion specification is interpreted literally"

That is, in the format argument of as.Date, you may include not only the conversion specification (introduced by %) but also the "other characters":

Furthermore, from ?as.Date:

Character strings are processed as far as necessary for the format specified: any trailing characters are ignored

Thus, this works:

as.Date("(u'9', u'2005', u'06')", format = "(u'%d', u'%Y', u'%m")
# [1] "2005-06-09"

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

...