KatyB
KatyB

Reputation: 3990

linear interpolation of points in R

This may seem a really simple question, but here goes:

I have a data frame:

test_df <- data.frame(x1 = c(277422033,24118536.4,2096819.0,
                               182293.4,15905,1330,105,16,1),
                      x2 = c(2.496e-3,2.495e-2,2.496e-1,
                               2.496e0,2.47e1,2.48e2,2.456e3,
                               3.7978e4,3.781e5))

and I would like to linearly interpolate this to increase the number of points. The variables are linearly related on a log scales, i.e.

plot(log10(test_df[,1]),log10(test_df[,2]))

enter image description here

So, my question is, how do I linearly interpolate these to increase the number of values?

Here is my attempt using a linear model (as opposed to the approx function):

I have defined a linear model as:

test.lm <- lm(log10(x1) ~ log10(x2), data = test_df)

and then define a new variable for the new points:

ss <- seq(min(test_df$x2),max(test_df$x2),length.out = 100) # new x1

then predict the new values and plot the points

newY <- predict(test.lm, newdata = data.frame(x2 = ss)) # interpolated values

test_df2 <- data.frame(x1 = 10^newY,
                       x2 = ss)

points(newY,log10(ss),col = "red")

enter image description here

This works as I expect i.e. the graph in the end is as I expected.

I would like to increase the number of points in test_df2 which can be done by increasing length.out e.g.

ss <- seq(min(test_df$x2),max(test_df$x2),length.out = 10000000)

but this makes the running time very long on my machine, to the point that I have to restart R.

Is there a way that I can linearly interpolate at an evenly distributed number of points which also extend the entire number of points specified in ss?

Upvotes: 0

Views: 447

Answers (1)

Insa
Insa

Reputation: 718

Just use

ss <- 10^seq(log10(min(test_df$x2)),log10(max(test_df$x2)),length.out = 1000)

to have your new data evenly distributed on the log scale.

Upvotes: 2

Related Questions