# [R] Interpolation Problems

Pedro.Rodriguez at sungard.com Pedro.Rodriguez at sungard.com
Tue Sep 2 17:53:38 CEST 2008

```Hi Steve,

It could be the case that you are trying to find values that are not in
the range of values you are providing.

For example,

x <- c(1,2,3,4,5)
y <- c(10,11,12,13,14)
xout <- c(0.01,0.02)
approx(x,y,xout,method="linear")

R's output:
\$x
 0.01 0.02

\$y
 NA NA

If you want to see the value of 10 when you Xs are below 1 and 14 when
the Xs are above 5, then code below may help.

Regards,

Pedro

interpolation_test	<- function(data,cum_prob,xout)
{
y	<- vector(length=length(xout))
for(i in 1:length(xout))
{
ValueToCheck <- xout[i]
j		<-1
while(cum_prob[j] < ValueToCheck && j < length(cum_prob) -2)
{
j <- j + 1
}

y0	<- data[j]
x0	<- cum_prob[j]

y1	<- data[j+1]
x1	<- cum_prob[j+1]

if(x0==ValueToCheck)
{
y[i] 	<- y0
} else {

y[i]	<- y0 +  (ValueToCheck-x0)*(y1-y0)/(x1-x0)
}
}
return(y)
}

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
On Behalf Of Steve Murray
Sent: Monday, September 01, 2008 6:17 PM
To: r-help at r-project.org
Subject: [R] Interpolation Problems

Dear all,

I'm trying to interpolate a dataset to give it twice as many values (I'm
giving the dataset a finer resolution by interpolating from 1 degree to
0.5 degrees) to match that of a corresponding dataset.

I have the data in both a data frame format (longitude column header
values along the top with latitude row header values down the side) or
column format (in the format latitude, longitude, value).

I have used Google to determine 'approxfun' the most appropriate command
to use for this purpose - I may well be wrong here though! Nevertheless,
I've tried using it with the default arguments for the data frame (i.e.
interp <- approxfun(dataset) ) but encounter the following errors:

> interp <- approxfun(JanAv)
Error in approxfun(JanAv) :
need at least two non-NA values to interpolate
In approxfun(JanAv) : collapsing to unique 'x' values

However, there are no NA values! And to double-check this, I did the
following:

> JanAv[is.na(JanAv)] <- 0

...to ensure that there really are no NAs, but receive the same error
message each time.

With regard to the latter 'collapsing to unique 'x' values', I'm not
sure what this means exactly, or how to deal with it.

use an alternative command (I want to perform a simple (e.g. linear)
interpolation), would be much appreciated.

Many thanks for any advice offered,

Steve

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help