Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert unix timestamp column to day of week in R

I am working with a data frame in R labeled "mydata". The first column, labled "ts" contains unix timestamp fields. I'd like to convert these fields to days of the week.

I've tried using strptime and POSIXct functions but I'm not sure how to execute them properly:

> strptime(ts, "%w")

--Returned this error:

"Error in as.character(x) : cannot coerce type 'closure' to vector of type 'character'"

I also just tried just converting it to human-readable format with POSIXct:

as.Date(as.POSIXct(ts, origin="1970-01-01"))

--Returned this error:

"Error in as.POSIXct.default(ts, origin = "1970-01-01") : do not know how to convert 'ts' to class “POSIXct”"

Update: Here is what ended up working for me:

> mydata$ts <- as.Date(mydata$ts)

then

> mydata$ts <- strftime( mydata$ts , "%w" )
like image 878
pas Avatar asked Jan 14 '23 04:01

pas


1 Answers

No need to go all the way to strftime when POSIXlt gives you this directly, and strftime calls as.POSIXlt.

wday <- function(x) as.POSIXlt(x)$wday

wday(Sys.time()) # Today is Sunday
## [1] 0

There is also the weekdays function, if you want character rather than numeric output:

weekdays(Sys.time())
## [1] "Sunday"
like image 169
Matthew Lundberg Avatar answered Jan 21 '23 13:01

Matthew Lundberg