我已经编写了一个UDF,其中我尝试连续运行4个while循环。它们是单独的循环,因为它们各自使用稍微不同的输入,但是当执行函数时,只有第一个while循环的结果存放在数据框中,我无法弄清楚原因。
我的代码在下面,应该是可执行的:
# polydata is a set of specific numbers, but here a random sample is fine.
polydata = sample(1:60, 91)
# User Defined Function - argument "f.day" is an integer, I have been testing with "5"
My.Function = function(f.day) {
# Fit polynomial
forecast.day = f.day
x = seq(forecast.day, forecast.day + 90, 1)
y.2 = coef(lm(polydata ~ x + I(x^2)))
y.3 = coef(lm(polydata ~ x + I(x^2)+(x^3)))
y.4 = coef(lm(polydata ~ x + I(x^2)+(x^3)+(x^4)))
y.5 = coef(lm(polydata ~ x + I(x^2)+(x^3)+(x^4)+(x^5)))
df = as.data.frame(matrix(NA, nrow = forecast.day+1, ncol = 4))
colnames(df) = c("Quadratic", "Cubic", "Quartic", "Quintic")
degree = 2
i = 0
df$Quadratic = c(rep(y.2[1], times = forecast.day + 1))
while(i <= forecast.day + 1){
j = 1
while(j <= degree){
df$Quadratic[i] = df$Quadratic[i] + y.2[j + 1] * i ^ j
j = j + 1
}
i = i + 1
}
degree = 3
i = 0
df$Cubic = c(rep(y.3[1], times = forecast.day + 1))
while(i <= forecast.day + 1){
j = 1
while(j <= degree){
df$Cubic[i] = df$Cubic[i] + y.3[j + 1] * i ^ j
j = j + 1
}
i = i + 1
}
degree = 4
i = 0
df$Quartic = c(rep(y.4[1], times = forecast.day + 1))
while(i <= forecast.day + 1){
j = 1
while(j <= degree){
df$Quartic[i] = df$Quartic[i] + y.4[j + 1] * i ^ j
j = j + 1
}
i = i + 1
}
degree = 5
i = 0
df$Quintic = c(rep(y.5[1], times = forecast.day + 1))
while(i <= forecast.day + 1){
j = 1
while(j <= degree){
df$Quintic[i] = df$Quintic[i] + y.5[j + 1] * i ^ j
j = j + 1
}
i = i + 1
}
return(df)
}
当我在测试脚本中运行该函数时,似乎只有第一个While循环正在完成:
> My.Frame = My.Function(5)
> My.Frame
Quadratic Cubic Quartic Quintic
1 39.43232 NA NA NA
2 38.54225 NA NA NA
3 37.66369 NA NA NA
4 36.79664 NA NA NA
5 35.94109 NA NA NA
6 35.09705 NA NA NA
是否缺少某些内容或是否无法在函数内运行连续循环?
谢谢!
答案 0 :(得分:0)
连续While循环可以在函数内运行,就像在普通脚本中一样。这里的错误是生成y.2, y.3, y.4, y.5
向量。这里系数被生成到特定的程度-2(二次),3(立方),4(四次)和5(五次)。
y.2是正确生成的,但其余部分缺少必要数量的I
元素,因此只为它们全部生成3个系数(这是仅二次方的正确数量)。因此,当j = 3(度)时,那么在df$Cubic[i] = df$Cubic[i] + y.3[j + 1] * i ^ j
中,它正在索引y.3 [4],这将给出NA,因为它不存在。
原始代码如下:
y.2 = coef(lm(polydata ~ x + I(x^2)))
y.3 = coef(lm(polydata ~ x + I(x^2)+(x^3)))
y.4 = coef(lm(polydata ~ x + I(x^2)+(x^3)+(x^4)))
y.5 = coef(lm(polydata ~ x + I(x^2)+(x^3)+(x^4)+(x^5)))
读作:
y.2 = coef(lm(polydata ~ x + I(x^2)))
y.3 = coef(lm(polydata ~ x + I(x^2)+I(x^3)))
y.4 = coef(lm(polydata ~ x + I(x^2)+I(x^3)+I(x^4)))
y.5 = coef(lm(polydata ~ x + I(x^2)+I(x^3)+I(x^4)+I(x^5)))
因此,当现在运行时,将根据请求的程度产生正确数量的系数,整个函数现在将产生完整的数据框。