简体   繁体   中英

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,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM