在R中使用interp1作为矩阵 [英] using interp1 in R for matrix
问题描述
我试图在R中使用interp1函数对矩阵进行线性插值,而不使用for循环.到目前为止,我已经尝试过:
I am trying to use the interp1 function in R for linearly interpolating a matrix without using a for loop. So far I have tried:
bthD <- c(0,2,3,4,5) # original depth vector
bthA <- c(4000,3500,3200,3000,2800) # original array of area
Temp <- c(4.5,4.2,4.2,4,5,5,4.5,4.2,4.2,4)
Temp <- matrix(Temp,2) # matrix for temperature measurements
# -- interpolating bathymetry data --
depthTemp <- c(0.5,1,2,3,4)
layerZ <- seq(depthTemp[1],depthTemp[5],0.1)
library(signal)
layerA <- interp1(bthD,bthA,layerZ);
# -- interpolate= matrix --
layerT <- list()
for (i in 1:2){
t <- Temp[i,]
layerT[[i]] <- interp1(depthTemp,t,layerZ)
}
layerT <- do.call(rbind,layerT)
因此,在这里,我在for循环的矩阵的每一行上使用了interp1.我想知道如何不使用for循环就可以做到这一点.我可以在Matlab中通过按如下方式转置矩阵来做到这一点:
So, here I have used interp1 on each row of the matrix in a for loop. I would like to know how I could do this without using a for loop. I can do this in matlab by transposing the matrix as follows:
layerT = interp1(depthTemp,Temp',layerZ)'; % matlab code
但是当我尝试在R中这样做
but when I attempt to do this in R
layerT <- interp1(depthTemp,t(Temp),layerZ)
它不返回插值结果矩阵,而是一个数字数组.如何确保R返回内插值的矩阵?
it does not return a matrix of interpolated results, but a numeric array. How can I ensure that R returns a matrix of the interpolated values?
推荐答案
-
您的方法没有错;我可能会避免使用中间
t <-
如果您想感到R-ish,请尝试
If you want to feel R-ish, try
apply(Temp,1,function(t) interp1(depthTemp,t,layerZ))
如果真的需要,您可能必须在所有内容前添加一个t(变位).
You may have to add a t(ranspose) in front of all if you really need it that way.
由于这是3d字段,因此按行插值可能不是最佳的.我最喜欢的是软件包
tgp
中的interp.loess
,但是对于常规间距,可以使用其他选项.该方法不适用于您的小型示例(适用于该问题),但需要使用较大的网格.Since this is a 3d-field, per-row interpolation might not be optimal. My favorite is
interp.loess
in packagetgp
, but for regular spacings other options might by available. The method does not work for you mini-example (which is fine for the question), but required a larger grid.这篇关于在R中使用interp1作为矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!