如何将非整数值作为小时添加到R中的日期作为输入向量的长度

时间:2018-01-12 17:49:21

标签: r

单位是小时。但我仍然有同样的问题,因为它没有添加所有的值。这是我的代码。

initialdates<-function(randomvariable){
  date_0<-"2017-01-01 00:00:00"
  vector_dates<-c(date_0)
  for(i in length(randomvariable)){
    vector_dates<-append(vector_dates,as.POSIXct("2017-01-01 00:00:00")+sum(randomvariable[1:i]))
  }
  return(vector_dates)
}


initialdates(randomvariablegenerator(100))

我得到的输出如下

"2017-01-01 00:00:00 cst"  "2017-01-01 00:03:47 cst"

为什么我没有从循环中获取所有其他元素

1 个答案:

答案 0 :(得分:1)

您可以将日期/时间转换为POSIXct格式并为其添加数字(包括小数)。

请注意,当您向POSIXct添加号码时,会将其添加为seconds

上述功能中的问题:

initialdates<-function(randomvariable){
  date_0<-"2017-01-01 00:00:00"
  vector_dates<-c(as.POSIXct(date_0))  #Convert to date before adding to vector
  for(i in 1:length(randomvariable)){  #loop should go 1:length(randomvariable)
    vector_dates<-append(vector_dates,as.POSIXct("2017-01-01 00:00:00")+sum(randomvariable[1:i]))
  }
  return(vector_dates)
}
# Random generated as described in OP
randomvariablegenerator <- function(n){
  return (42*rbeta(n,.123,2.77))
}

# Test type of value function is returning. Test with n = 3 (small value)
ret_val <- initialdates(randomvariablegenerator(3))

#> str(ret_val)
# POSIXct[1:4], format: "2017-01-01 00:00:00" "2017-01-01 00:00:00" "2017-01-01 # 00:00:24" ...
# Returned value is in POSIXct format (date/time)
> as.POSIXct("2017-01-01 00:00:00") + 100  #100 is converted in 1 min
[1] "2017-01-01 00:01:40 GMT"   #100 is converted in 1 min, 40 seconds

> as.POSIXct("2017-01-01 00:00:00") + 600
[1] "2017-01-01 00:10:00 GMT"    #600 is converted in 6 min. 

> as.POSIXct("2017-01-01 00:00:00") + 2 * 60 * 60
[1] "2017-01-01 02:00:00 GMT"     #2 hours has been added

> as.POSIXct("2017-01-01 00:00:00") + 2.5 * 60 * 60
[1] "2017-01-01 02:30:00 GMT"   #2 hours has been added

#You can even add decimal of seconds(up to millisecond accuracy) i.e
> a <- as.POSIXct("2017-01-01 00:00:00") + 10.6
> a
[1] "2017-01-01 00:00:10 GMT"    #Make a note that 0.6 sec is hidden part

> a <- a + 10.4   #add 10.4
> a
[1] "2017-01-01 00:00:21 GMT"  # 0.6 hidden part is added with 0.4 to make it 21