Interpolate a one-dimensional vector to specified new size in R

Viewed 56

How do I interpolate, lets say a 10 numeric list/vector in R to a specified new size (eg. size=6)?

ls <- c(1:10) # size 10

Resulting in something like:

ls_interp <- ... # interpolate

> ls_interp
[1] 1 2 4 6 8 10
2 Answers

Try this:

ls_interp <- approx( x, n=6 )$x
ls_interp

It outputs: [1] 1.0 2.8 4.6 6.4 8.2 10.0

In reality it gives you back both x's and y's (but you only really need the one in this case)

Another option is using seq (but I believe approx method by @Sirius is better)

> seq(min(ls), max(ls), length.out = 6)
[1]  1.0  2.8  4.6  6.4  8.2 10.0

or

> min(ls) + (length(ls) - 1) / 5 * (seq(6) - 1)
[1]  1.0  2.8  4.6  6.4  8.2 10.0
Related