我的数据如下:
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)
我想线性插值c1,c16,c30
以找到其间的值,即c2,c3,c4,......c15
然后c17,c18,c19,..........c29
。
这可能使用R吗?
答案 0 :(得分:1)
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)
修改强>
如果要将输出添加为文本文件:
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')))