mr.T
mr.T

Reputation: 634

interpolation of a vector by another vector

I have a vector "x" I can interpolate it on "n" points, let's say 20

x <- c(1,2,1,2,1,2,1)
n <- 20
ap <- approx(x,n = n)$y

as a result I will get something like this enter image description here

"n" is a constant, the question is - can I use "n" as a vector

n <- c(1:10,10:1)

to get something like this enter image description here

Or maybe there is another way to do this?

Sorry for such an unclear question, but I don't know how to ask otherwise.

Upvotes: 1

Views: 92

Answers (2)

GKi
GKi

Reputation: 39737

Maybe you can use approxfun in combination with rep and cumsum to come to the desired output:

x <- c(1,2,1,2,1,2,1)
n <- c(1:10,10:1)
i <- cumsum(c(0,rep(1/n, n)))
i <- i - min(i)
i <- 1 + i / max(i) * (length(x) - 1)
approxfun(x)(i)

Upvotes: 1

dcarlson
dcarlson

Reputation: 11076

There are two ways to interpret your question. In your example, the vector x should be y since only provided one vector:

approx(x, n = n)   # Your code
# $x
#  [1] 1.000000 1.315789 1.631579 1.947368 2.263158 2.578947 2.894737 3.210526 3.526316 3.842105 4.157895 4.473684 4.789474 5.105263 5.421053 5.736842 6.052632 6.368421 6.684211
# [20] 7.000000
# 
# $y
#  [1] 1.000000 1.473684 1.947368 2.421053 2.828947 3.223684 3.618421 3.802632 3.881579 3.960526 4.039474 4.118421 4.197368 4.381579 4.776316 5.171053 5.578947 6.052632 6.526316
# [20] 7.000000
approx(x=1:7, y=x, n=n)  # How approx() interpreted your code
# $x
#  [1] 1.000000 1.315789 1.631579 1.947368 2.263158 2.578947 2.894737 3.210526 3.526316 3.842105 4.157895 4.473684 4.789474 5.105263 5.421053 5.736842 6.052632 6.368421 6.684211
# [20] 7.000000
# 
# $y
#  [1] 1.000000 1.473684 1.947368 2.421053 2.828947 3.223684 3.618421 3.802632 3.881579 3.960526 4.039474 4.118421 4.197368 4.381579 4.776316 5.171053 5.578947 6.052632 6.526316
# [20] 7.000000

If your question means can x be a vector with unequal spacing, the answer is yes. You could have used x <- c(1, 2.5, 3.75, 4, 4.25, 5.5, 7) and y <- c(1, 2, 1, 2, 1, 2, 1).

If you wanted equal spacing for the approximation but then want to interpolate new values at unequal intervals, the answer is still yes, but you have to use approxfun which creates a function:

apxfun <- approxfun(c(1,2,1,2,1,2,1))
vec2 <- c(1, 1.5, 2.0, 2.5, 3.0, 3.2, 3.4, 3.6, 3.8, 3.95, 4.05, 4.2, 4.4, 4.6, 4.8, 5.0, 5.5, 6.0, 6.5, 7)
apxfun(vec2)
#  [1] 1.00 1.50 2.00 1.50 1.00 1.20 1.40 1.60 1.80 1.95 1.95 1.80 1.60 1.40 1.20 1.00 1.50 2.00 1.50 1.00

Upvotes: 0

Related Questions