KatyB
KatyB

Reputation: 3990

using interp1 in R for matrix

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)

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

but when I attempt to do this in R

layerT <- interp1(depthTemp,t(Temp),layerZ)

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?

Upvotes: 2

Views: 2219

Answers (1)

Dieter Menne
Dieter Menne

Reputation: 10215

  • There is nothing wrong with your approach; I probably would avoid the intermediate t <-

  • If you want to feel R-ish, try

apply(Temp,1,function(t) interp1(depthTemp,t,layerZ))

You may have to add a t(ranspose) in front of all if you really need it that way.

Since this is a 3d-field, per-row interpolation might not be optimal. My favorite is interp.loess in package tgp, 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.

Upvotes: 1

Related Questions