Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 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 Answer

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...