2017-06-09 61 views
0

我需要一些帮助。我目前正试图将线性模型拟合为小时电价。所以,我正在考虑创建一个假人,如果一天中的小时在06:00到20:00之间,则假人的值为1。不幸的是,我一直在努力。在当天的特定时段创建虚拟变量

time.cet <- as.POSIXct(time.numeric, origin = "1970-01-01", tz=local.time.zone) 
hours.S <- strftime(time.cet, format = "%H:%M:%S", tz=local.time.zone) 
head(time.cet) 
[1] "2007-01-01 00:00:00 CET" "2007-01-01 01:00:00 CET" "2007-01-01 02:00:00 CET" 
[4] "2007-01-01 03:00:00 CET" "2007-01-01 04:00:00 CET" "2007-01-01 05:00:00 CET" 

我希望有人能帮忙。

+0

什么是你的输入?你想如何输出?你想要一个带有列日期和相应的0/1值的data.frame,或者只是0/1的矢量,因为日期已经存储在其他地方了?请提供一些数据/信息来处理... – digEmAll

回答

1

ifelse()语句是创建虚拟变量的便捷方式。我不太了解如何亲自处理时间,但创建一个虚拟变量的形式类似于: dummy <- with(data, ifelse(time > 06:00 & time < 20:00, 1, 0) 无论数据被调用的是什么数据,而时间是您的时间存储的列。如果时间不像正常的数字向量(我假设他们会这样做),那么需要稍微调整一下条件。

2

当我做了时间截止时,我喜欢将截断值作为对象。这样,如果您需要更改截断值,则更改对象的值而不是条件语句中的值会更容易。

我下面的代码使用了lubridate(),这是一个很好的管理时间/日期的包。

我在下面的代码应该给你需要在分析中加​​入一个虚拟变量的信息。

### 
### Load Package 
### 

library(lubridate) 

### 
### Designate Time Cut-Offs 
### 

Beginning <- hms("06:00:00") 
End <- hms("20:00:00") 

### 
### Designate Test Cut-Offs 
### 

Test.1 <- hms("5:00:00") 
Test.2 <- hms("11:00:00") 

### 
### Test Conditional Logic 
### 
### Value will be 1 if time is between, value will be 0 if it is not. 
### 

ifelse(((Test.1 >= Beginning) & (Test.1 <= End)) , 1, 0) 

########## This should (and does) return a 0 

ifelse(((Test.2 >= Beginning) & (Test.2 <= End)) , 1, 0) 

####### This should (and does) return a 1 

### 
### Create New Variable On Previous Data Frame (Your.DF) named Time.Dummy 
### 
### Value for new variable will be 1 if time is between, value will be 0 if it is not. 
### 

Your.DF$Time.Dummy <- ifelse(((time.cet >= Beginning) & (time.cet <= End)) , 1, 0) 
1
library(lubridate) 

# Create fake data 
set.seed(2) 
dat = data.frame(time = seq(ymd_hms("2016-01-01 00:00:00"), ymd_hms("2016-01-31 00:00:00"), by="hour")) 
dat$price = 1 + cumsum(rnorm(nrow(dat), 0, 0.01)) 

# Create time dummy 
dat$dummy = ifelse(hour(dat$time) >=6 & hour(dat$time) <= 20, 1, 0) 
1

尝试包括可重复的代码下一次。看起来你缺少time.numeric例如。我不得不做一些随机的时间。

time.cet <- c(ymd_hms("2007-01-01 00:00:00"), 
       ymd_hms("2007-01-01 06:00:00"), 
       ymd_hms("2007-01-01 12:00:00")) 
time.cet 

[1] "2006-12-31 18:00:00 CST" "2007-01-01 00:00:00 CST" "2007-01-01 06:00:00 CST" 

请注意时区问题,这对解决方案并不重要。

您可以使用dplyr::betweenlubridate::hour得到的TRUE/FALSE(或1/0)的列表为X时间是否A & B之间。

library(dplyr) 
library(lubridate) 

A <- 6 
B <- 20 
between(hour(time.cet), A, B) 
[1] TRUE FALSE TRUE 

注意between是包容>= & <=