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" )
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With