简体   繁体   中英

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, ie

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

在此处输入图片说明

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")

在此处输入图片说明

This works as I expect ie 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 eg

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM