Convert unix timestamp column to day of week in R

让人想犯罪 __ 提交于 2020-02-21 03:00:59

问题


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" )

回答1:


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"


来源:https://stackoverflow.com/questions/17007023/convert-unix-timestamp-column-to-day-of-week-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!