Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interpolate between to vectors using R?

My data look like:

 c1=c(2,5,5,5,8,4,5,4)
 c16=c(40,50,65,75,38,14,45,64)
 c30=c(20,41,35,15,18,14,15,14)

I would like to linearly interpolate c1,c16,c30 to find the values in between i.e. c2,c3,c4,......c15 then c17,c18,c19,..........c29.

IS this possible using R?

like image 628
temor Avatar asked Dec 10 '25 19:12

temor


1 Answers

You align your vector in a matrix with rbind and use apply on each column to do the interpolation (done by approxfun):

funcs = apply(rbind(c1,c16,c30), 2, approxfun, x=c(1, 16, 30))

Here is the interpolation on points (1, 2), (16, 40), (30, 20):

#> funcs[[1]](1)
#[1] 2

#> funcs[[1]](16)
#[1] 40

#> funcs[[1]](30)
#[1] 20

#funcs[[1]](1:30)
# [1]  2.000000  4.533333  7.066667  9.600000 12.133333 14.666667 17.200000 19.733333 22.266667 24.800000 27.333333 29.866667 32.400000 34.933333 37.466667
#[16] 40.000000 38.571429 37.142857 35.714286 34.285714 32.857143 31.428571 30.000000 28.571429 27.142857 25.714286 24.285714 22.857143 21.428571 20.000000

Here are all interpolations plotted with ggplot:

dfs = Map(function(f, i) data.frame(x=1:30,y=f(1:30),interp=i), funcs, seq(length(funcs)))

library(ggplot2)

df = do.call(rbind, dfs)
ggplot(df, aes(x=x,y=y, color=as.character(interp))) + geom_line(size=1.2)

enter image description here

Edit:

If you want to add output as text files:

m = do.call(rbind, lapply(funcs, function(f) f(1:30)))
lapply(1:ncol(m), function(i) write.table(m[,i], file=paste0('c',i,'.txt')))
like image 124
Colonel Beauvel Avatar answered Dec 13 '25 07:12

Colonel Beauvel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!