Masi Masi - 20 days ago 6
R Question

How to use R interp1 similarly as MATLAB's?

I am trying to interpolate linearly in R.
Pseudocode is

u = interp1(u, linspace(1, numel(u), numel(u)-1));
in MATLAB where extrapolation returns NaN if the point is outside the domain (default, more here).


  • approx rule=1
    is equivalent to MATLAB pseudocode



I am not sure about the second
interp1
parameter what is not required in MATLAB so I just let unsuccessufully
y <- x
such that

interp1(x, y, xi, method = "linear")


Minimal code example (real one has > 500 k points so linear will work) and its output at the top

List of 2
$ : num [1:3] 1 2 3
$ : num [1:2] 1 2
num [1:2] 0 1
Error in interp1(x, y, xi, method = "linear") :
Points 'xi' outside of range of argument 'x'.
Execution halted

library("pracma") # http://finzi.psych.upenn.edu/library/pracma/html/interp1.html

files <- vector("list", 2)
files[[1]] <- c(1,2,3)
files[[2]] <- c(1,2)
str(files)

# Wanted, MATLAB: u = interp1(u, linspace(1, numel(u), numel(u)-1));

xi <- seq(0,1, len = length(files[[1]]) - 1)
x <- files[[1]]
y <- files[[1]]
str(xi)

files[[1]] <- interp1(x, y, xi, method = "linear")

str(files)


I know the thread using interp1 in R for matrix but I do not have a matrix.

Input:
c(1,2,3)


Expected output: [1:2] datastructure

R: 3.3.1

OS: Debian 8.5

Answer

If you're willing to get NA values on extrapolation, as is the default for linear interpolation/extrapolation in interp1, then approx() works fine:

files <- list(1:3,1:2)
xi <- seq(0,1, len = length(files[[1]]) - 1)
x <- files[[1]]
y <- files[[1]]
a <- approx(x,y,xi)

You said you wanted just a two-element vector so presumably you just want the output y-values:

a$y
## [1] NA  1

This may seem wrong, but is the correct answer to the question you actually posed. You've used files[[1]] for both x and y, so approx() should return y=x when the input is in the range from 1 to 3, and NA otherwise. In this case xi is [0 1], so the first element is out of the range of the x/y data provided ...

PS I can appreciate wanting to use pracma for similarity to MATLAB's syntax, but - although pracma is high-quality and widely used - base R functions are even more widely used/thoroughly tested ...

Comments