문제

I have a set of data, for example:

x<-c(1, 2, 3, 4, 5, 6)
y<-c(100, 110, 121, 133.1, NA, 161.051)

Now, y is clearly increasing at a constant rate of 10%.

I want to be able to interpolate the data at x=5, and I want to print 146.41 as the answer. However, this function doesn't seem to do it:

approx(x,y,5)

This prints 147.0755, which is not the answer i'm looking for.

approx(x,y,5,method="constant")

doesn't do the trick either.

Where am I going wrong?

도움이 되었습니까?

해결책

Since you are dealing with rates, you need to translate y into log(y), interpolate, then use exp to get the result back into a linear scale:

exp(approx(x, log(y), x)$y)
# [1] 100.000 110.000 121.000 133.100 146.410 161.051

다른 팁

short answer is you can't without giving it some more info, because it's either a linear fit, which doesn't deal with a non-linear function, or a constant fit, which also doesn't.

You can force it by telling it that the right hand point is 1.1x the emphasis of the left hand point:

approx(x,y,5, method="constant", f=1/2.1) # 1/ left weight (1) + right weight (1.1)

>$x
>[1] 5

>$y
>[1] 146.41

but that's probably not all that useful!

probably the closest you can get is:

spline(x,y,xout=5)

>$x
>[1] 5
>$y
>[1] 146.4125

Not very elegant but you can replace missing values, using geometric series formula :

  y[is.na(y)] <- y[1]*(1+diff(y)[1]/y[1])^(which(is.na(y))-1)
y
[1] 100.000 110.000 121.000 133.100 146.410 161.051
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top