meolic
meolic

Reputation: 1207

R: approxfun complains about "object cannot be coerced to type 'double'"

I have a solution similar (even simpler) to this: How to interpolate data in R

But it is not working for me. I have used dput to take a snapshot of my data.

  a <- structure(list(
    time = structure(
       c(1566381574.097, 1566381542.104, 1566381510.109, 1566381390.134, 1566381330.118,
         1566381300.107, 1566381240.114, 1566381210.114, 1566381173.903, 1566381148.113
       ), class = c("POSIXct", "POSIXt"), tzone = ""),
    value = c(164.1, 162.3, 161.1, 158.6, 159.6, 157.6, 159, 157.8, 155.3, 155.3
  )), class = "data.frame", row.names = c(NA, 10L))

  b <- structure(list(time = structure(
    c(1566381120, 1566381180, 1566381240, 1566381300, 1566381360, 1566381420, 1566381480, 1566381540
    ), class = c("POSIXct", "POSIXt"), tzone = "")), row.names = c(NA, 8L), class = "data.frame")

  head(a)
  head(b)

  result <- b
  result$value <- approxfun(a$time,a$value)(b)

This is, what I get:

>   head(a)
                 time value
1 2019-08-21 11:59:34 164.1
2 2019-08-21 11:59:02 162.3
3 2019-08-21 11:58:30 161.1
4 2019-08-21 11:56:30 158.6
5 2019-08-21 11:55:30 159.6
6 2019-08-21 11:55:00 157.6
>   head(b)
                 time
1 2019-08-21 11:52:00
2 2019-08-21 11:53:00
3 2019-08-21 11:54:00
4 2019-08-21 11:55:00
5 2019-08-21 11:56:00
6 2019-08-21 11:57:00
>   
>   result <- b
>   result$value <- approxfun(a$time,a$value)(b)
Error in .approxfun(x, y, v, method, yleft, yright, f) : 
  (list) object cannot be coerced to type 'double'

Upvotes: 1

Views: 286

Answers (1)

akrun
akrun

Reputation: 887078

According to ?approxfun

The function approxfun returns a function performing (linear or constant) interpolation of the given data points. For a given set of x values, this function will return the corresponding interpolated values. Here, the 'b' is a data.frame, may be we need

x, y - numeric vectors giving the coordinates of the points to be interpolated.

Based on the decription, as the approxfun is returning a function and it interpolates based on a set of x (numeric vector), passing a data.frame will not work. So, extract the specific column as vector for interpolation

approxfun(a$time,a$value)(b$time)

Upvotes: 2

Related Questions