【求帮助】拉格朗日插值法-补值

setwd("C:/Users/DELL1/Desktop")

library(XLConnect)

lagrange<-function(x,xi,yi){
n<-length(xi)
lage<-0
for(i in 1:n){
li<-1
for(j in 1:n){
if(i!=j)
li<-li*(x-xi[j])/(xi[i]-xi[j])
}
lage<-li*yi[i]+lage
}
return(lage)
}

missdata = missing_data

for(k in 1:3)
{
x = which(is.na(missing_data[,k]))
x1=c(0,x)
x2=c(x,nrow(missing_data))
x12 = x2-x1-1
xx1<-x12[1:(length(x12)-1)] #缺失值前面的行数
xx2<-x12[2:(length(x12))] #缺失值后面的行数

j = 1
for(m in x)
{
if(xx1[j]>=5)        #空值前的判断
xi<- (m-5):(m-1)
else
xi<-(m-xx1[j]):(m-1)

if(xx2[j]>=5)          #空值后的判断
xi<-c(xi,(m+1):(m+5))
else
xi<-c(xi,(m+1):(m+xx2[j]))

yi=missing_data[xi,k]
missdata[m,k]=lagrange(m,xi,yi)
print(c(m,missdata[m,k]))
j =j+1
}


}

21*3的表格
235.8333 324.0343 478.3231
236.2708 325.6379 515.4564
238.0521 328.0897 517.0909
235.9063 　 514.89
236.7604 268.8324
404.048 486.0912
237.4167 391.2652 516.233
238.6563 380.8241
237.6042 388.023 435.3508
238.0313 206.4349 487.675
235.0729
235.5313 400.0787 660.2347
411.2069 621.2346
234.4688 395.2343 611.3408
235.5 344.8221 643.0863
235.6354 385.6432 642.3482
234.5521 401.6234
236 409.6489 602.9347
235.2396 416.8795 589.3457
235.4896 　 556.3452
236.9688 　 538.347

[1] 6.0000 237.1512
[1] 13.000 235.315
[1] 4.0000 203.4621
[1] 11.0000 237.3481
[1] 20 NA
[1] 21 NaN
[1] 5.0000 503.7444
[1] 8.0000 472.0948
[1] 11.0000 634.3942
[1] 17.0000 615.7713