Reputation: 147
I have a vector dates with elements in the same format, like element 1 "Mon, 05 Sep 2013 01:19:18 -0000" . I am trying to turn this vector into a data frame so I can manipulate them. For instance, I would like to be able to subtract 4 days from the first entry and get "Thu, 01 Sep 2013 01:19:18 -0000". I would also like to plot each element on a time line.
I have tried
as.Date(dates,'%a, %d %b %z %H:%M:%S %z')
and
for (d in dates){
as.Date(d,'%a, %d %b %z %H:%M:%S -%z')
}
but I always get NA.
Upvotes: 1
Views: 63
Reputation: 7755
You were very close. Try:
dates <- c("Mon, 05 Sep 2013 01:19:18 -0000", "Thu, 01 Sep 2013 01:19:18 -0000")
strptime(dates, '%a, %d %b %Y %H:%M:%S %z')
You just had a typo in the year argument (should be %Y
, not %z
). If you want to store the time as a date, add as.Date
as you have done
as.Date(dates, '%a, %d %b %Y %H:%M:%S %z')
If you want to make a data.frame and subtract 4 days from each date, try:
data.frame(date = strptime(dates, '%a, %d %b %Y %H:%M:%S %z'),
subtracted = strptime(dates, '%a, %d %b %Y %H:%M:%S %z') - as.difftime(4, unit="days"))
Note that R returns your system-specific times, which might differ from the times in your vector as specified by the %z
argument (see ?strptime
).
Upvotes: 1