将UNIX时间戳列转换为R中的星期几
我正在使用 R 中标有"mydata"的数据框.第一列标记为"ts",其中包含unix时间戳字段.我想将这些字段转换为一周中的几天.
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.
我尝试使用strptime和POSIXct函数,但不确定如何正确执行它们:
I've tried using strptime and POSIXct functions but I'm not sure how to execute them properly:
> strptime(ts, "%w")
-返回此错误:
"as.character(x)中的错误:无法将类型'closure'强制转换为类型为'character'的向量"
"Error in as.character(x) : cannot coerce type 'closure' to vector of type 'character'"
我也尝试过使用POSIXct将其转换为人类可读的格式:
I also just tried just converting it to human-readable format with POSIXct:
as.Date(as.POSIXct(ts, origin="1970-01-01"))
-返回此错误:
"as.POSIXct.default(ts,origin ="1970-01-01")中的错误:不知道如何将"ts"转换为"POSIXct"类"
"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)
然后
> mydata$ts <- strftime( mydata$ts , "%w" )
当 POSIXlt
直接为您提供此功能且 strftime
调用 as.POSIXlt
.
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
如果想要字符而不是数字输出,还可以使用 weekdays
函数:
There is also the weekdays
function, if you want character rather than numeric output:
weekdays(Sys.time())
## [1] "Sunday"