简体   繁体   中英

Spline interpolation for values for time

One column with time and date values, and the other with values of speed, I would like to interpolate the value of speed for any given time as below, but I am getting an error.

This is the data set.

 startTimestamp        avg_Speed
 2016-04-11 00:01:07   74.45
 2016-04-11 00:05:10   73.58
 2016-04-11 00:06:09   89.90 

I want to interpolate the value of speed at say - "00:03:11", I just used the spline function as so,

newspeed <- splinefun(k$startTimestamp, k$avg_Speed, method = "monoH.FC")
newspeed("00:03:11")

And this is the error I get.

Error in if (extrapol == "linear" && any(iXtra <- (iL <- (i == 0)) | (iR ...

Some additional information: class(f$startTimestamp) = "POSIXct" "POSIXt"

I think it'll solve your problem easily to change class into numeric (min).

# making data (you needn't)
k <- data.frame(startTimestamp = c("2016-04-11 00:01:07", "2016-04-11 00:05:10", "2016-04-11 00:06:09"),
                avg_Speed = c(74.45, 73.58, 89.90))
k[,1] <- as.POSIXct(k[,1], "GMT")

# changing class ( POSIXct -> difftime -> numeric )
zero_time <- as.POSIXct("2016-04-11 00:00:00", "GMT") # using your time zone
k$difftime <- as.numeric(difftime(k$startTimestamp, zero_time))
class(k$difftime)  ## "numeric" (min)

# interpolate
newspeed <- splinefun(k$difftime, k$avg_Speed, method = "monoH.FC")
newspeed( 3 + 11/60 )   # or newspeed( as.numeric(as.difftime("00:03:11")) )
          ## results [1] 69.66494

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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