简体   繁体   中英

How to cleanly use interpolation between points to generate a mean in R

I am having issues trying to generate a code that will cleanly produce a mean (specifically a weighted average) based on a simple plot of points using interpolation.

For Example;

ex=c(1,2,3,4,5)
why=c(2,5,9,15,24)

This shows the kind of information I am working with.

plot(ex, why, type="o")

At this point, I want to actually have each point "binned" so the lines between them are straight. To do this, I have been adding points to the x values manually in excel as (x+0.01). This is the new output:

why=c(2,2,5,5,9,9,15,15,24,24)
ex=c(1,2,2.01,3,3.01,4,4.01,5,5.01,6)
plot(ex, why, type="o")

So this is where my question comes in to play. I have to do this many times and do not want to generate a ton of new vectors and objects. To get a weighted average, I have been interpolating y values for increments of x at 0.01 using interpolation into a new object. I am then able to go into this new object and get a mean when a point falls between the actual ex values, ie

mean(newy[1:245])

Because I made new y values for 100 increments of x that (basically) follow a straight line, I am getting a weighted average here for x= 1 to 2.45.

Is there an easier and more elegant way to embed the interpolate code into the mean code so I could just say "average of interpolated y for nonreal x to nonreal x?"

It doesn't do exactly what you want, but you should consider the stepfun function -- this creates a step function out of two series.

plot(stepfun(ex[-1], why))

stepfun is handy because it gives you a function defined over that interval, so you can easily interpolate just by evaluating anywhere. The downside to it is that it is not strictly defined on the range given (which is why we have to cut off the first value in ex ).

阶跃函数

Based on your second plotting example, I think you are probably looking for this:

library(ggplot2)
qplot(ex, why, geom="step")

this gives:

在此处输入图片说明

Or if you want the line to go vertical first, you can use:

qplot(ex, why, geom="step", direction = "vh")

which gives:

在此处输入图片说明

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