0
votes

I have a list of data frames, xyz, and in every data frame there are 2 numeric vectors (x and y). I want to apply the interpSpline function from package splines to x and y, but when I do :

lapply(xyz, function (x){
x%>%
interpSpline(x,y)
})

I get the following error:

Error in data.frame(x = as.numeric(obj1), y = as.numeric(obj2)) :
(list) object cannot be coerced to type 'double'

2

2 Answers

0
votes

It doesn't work because interpSpline doesn't take a data frame as its first argument.

xyz <- list(data.frame(x=rnorm(10),y=rnorm(10)),
            data.frame(x=rnorm(10),y=rnorm(10)))
library(splines)
sf <- function(d) with(d,interpSpline(x,y)))
s <- lapply(xyz,sf)

You could also use interpSpline(d$x,d$y). It might be possible to do enough contortions to get interpSpline to work with pipes, but it hardly seems worth the trouble ...

0
votes

Per your comment on Ben's answer, interpSpline() requires the input x values to be unique. So, to avoid this error you could use the spline() function instead of interpSpline(). This will set s equal to the interpolated values of the spline at each x,y input coordinate. However, you will not have all the other output that you get from interpSpline().

set.seed(1)
# fake up some data that has duplicate 'x' values
xyz <- list(data.frame(x=round(rnorm(100),1),y=round(rnorm(100),1)),
            data.frame(x=round(rnorm(100),1),y=round(rnorm(100),1)))
library(splines)
sf <- function(d) with(d,spline(x,y))
s <- lapply(xyz,sf)