为一天中的每个小时创建虚拟对象

问题描述 投票:0回答:1

我很惊讶我在这个网站上找不到可以回答我的问题。

我想为一天中的每个小时创建24个虚拟变量(如果时间是一天中的该小时,则值为1,否则为0)。数据的一小部分看起来像这样:

       df <- as.POSIXct(c("08-01-2018 19:46", "08-01-2018 19:50", "08-01- 
       2018 20:46", "09-01-2018 21:17"), format = "%d-%m-%Y %H:%M")

       [1] "2018-01-08 19:46:00 CET" "2018-01-08 19:50:00 CET" "2018-01-08 
       20:46:00 CET" "2018-01-09 21:17:00 CET"

我希望输出像这样:

           19 20 21
        1:  1  0  0
        2:  1  0  0
        3:  0  1  0
        4:  0  0  1

我已经看过这个问题:Creating a dummy variable for certain hours of the day

我对问题的唯一回答是,对于每种情况,我必须编写24条ifelse语句。

我想知道是否有一种更优雅的方式来获得此输出而不必编写24条ifelse语句。

如果该问题重复,请告诉我!

谢谢,

RC

r
1个回答
1
投票

这样可以吗?如果需要as.data.frame,可以在输出中使用data.frame

library(lubridate)
hours <- as.factor(lubridate::hour(df))

# with intercept
model.matrix(~hours)

# without intercept - (+0)
model.matrix(~hours+0)

进一步阅读:

Generate a dummy-variable

https://stats.stackexchange.com/questions/174976/why-does-the-intercept-column-in-model-matrix-replace-the-first-factor

© www.soinside.com 2019 - 2024. All rights reserved.