简体   繁体   English

将unix时间戳列转换为R中的星期几

[英]Convert unix timestamp column to day of week in R

I am working with a data frame in R labeled "mydata". 我正在使用R标记为“mydata”的数据框。 The first column, labled "ts" contains unix timestamp fields. 标有“ts”的第一列包含unix时间戳字段。 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和POSIXct函数,但我不确定如何正确执行它们:

> strptime(ts, "%w")

--Returned this error: - 返回此错误:

"Error in as.character(x) : cannot coerce type 'closure' to vector of type 'character'" “as.character(x)中的错误:无法强制将'闭合'类型强制转换为'character'类型的向量”

I also just tried just converting it to human-readable format with POSIXct: 我也尝试过用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”" “as.POSIXct.default(ts,origin =”1970-01-01“)中的错误:不知道如何将'ts'转换为类”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 . POSIXlt直接给你这个时, POSIXlt一直到strftime ,而strftime调用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功能:

weekdays(Sys.time())
## [1] "Sunday"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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