Cybernetic
Cybernetic

Reputation: 13334

Convert timestamp column in dataframe to day of year in R

I have a dataframe in R where one of the columns is a timestamp such as 2014-03-08 00:20:34

I would like to convert all of these timestamps in the dataframe to the day of the year. For example, March 29, 2014 would be 88.

This will do the conversion if 'df' is my dataframe and 'updated' is my timestamp column:

strftime(df$updated, format = "%j")

How can I apply this across the entire dataframe?

Thanks,

Upvotes: 0

Views: 727

Answers (1)

IRTFM
IRTFM

Reputation: 263342

as.numeric(as.Date("2014-03-08 00:20:34")-as.Date("2014-01-01"))+1
#[1] 67

So just use an assignment to whatever name column you want and replace df$updated for the character value. The other way would be with POSIXlt objects which are really multi-element named lists:

as.POSIXlt("2014-03-08 00:20:34")$yday
[1] 66
as.POSIXlt("2014-03-08 00:20:34")$yday +1 
[1] 67   #b ecause `yday`s` are zero referenced unlike the rest of R

Upvotes: 1

Related Questions