內插法

352 views
Skip to first unread message

Hsia

unread,
May 9, 2017, 3:31:08 AM5/9/17
to R軟體使用者論壇
用R語言寫出內插法公式 求X的值
Ex
7 14 X 12 9
5 X 24 X 13
6 X 22 16 12
X 20 21 17 10
10 19 25 X 14

WEPA ^_^

unread,
May 9, 2017, 8:49:40 AM5/9/17
to R軟體使用者論壇
Hi Ys,

內插法公式是計算數值X滿足什麼條件???

Ys於 2017年5月9日星期二 UTC+8下午3時31分08秒寫道:

Ys

unread,
May 10, 2017, 10:46:46 PM5/10/17
to R軟體使用者論壇
X就是NA 然後要求出NA的值,好像是要用for迴圈寫,可是我寫到一半就不會了
for(j in 1:ncol(x)) {
for(i in 1:now(x)) {
.......
}
}

WEPA ^_^

unread,
May 11, 2017, 12:34:19 PM5/11/17
to R軟體使用者論壇
Hi Ys,

Please try:


# title: Linear interpolation
# date: 2017.5.11

y <- read.table(text="
7    14   X   12    9
5     X   24   X   13
6     X   22  16   12
X    20  21  17   10
10  19   25   X   14", stringsAsFactors=FALSE)
y <- c(t(as.matrix(y, ncol=5)))
y[y == "X"] <- NA
y <- as.numeric(y)
x <- c(1:length(y))

yNaIndex <- which(is.na(y))

# method 1. Using approxfun {stats}
myApprox <- approx(x, y, xout=yNaIndex) # list
y[yNaIndex] <- myApprox$y

# method 2. Using linear interpolation, y=mx+b
yLinearInterpolation <- c()
for (i in yNaIndex) {
  m <- (y[i+1] - y[i-1])/(x[i+1] - x[i-1]) # slope
  b <- y[i-1] - (m*x[i-1])                 # intercept
  yLinearInterpolation <- c(yLinearInterpolation, m*i + b)
}

y[yNaIndex] # approxfun
yLinearInterpolation # linear interpolation (same as approxfun function)

# visualization
plot(x, y, type="b", main="Linear interpolation")
points(myApprox, col="red", pch=16)
# end

Ys於 2017年5月11日星期四 UTC+8上午10時46分46秒寫道:

Ys

unread,
May 15, 2017, 10:58:11 AM5/15/17
to R軟體使用者論壇
您好 , 謝謝您這麼用心地幫我解答,不過我只是學基礎的R語言,您寫的算式有些看不懂,可以請您幫我看看能否用FOR迴圈寫出嗎,這題我卡很久了QQ

WEPA ^_^

unread,
May 16, 2017, 6:44:59 AM5/16/17
to R軟體使用者論壇
Hi Ys,

上面程式中 method 2 是採用FOR迴圈撰寫, 請再參考該程式. 加油!

Ys於 2017年5月15日星期一 UTC+8下午10時58分11秒寫道:
Reply all
Reply to author
Forward
0 new messages