【发布时间】:2017-09-05 14:09:52
【问题描述】:
我编写了一个 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
是否缺少某些内容,或者只是无法在函数内运行连续循环?
谢谢!
【问题讨论】:
-
我不确定您要做什么。但就代码而言,您从 degree = 3 开始,您为 ys 提供了错误的索引(例如,y.3、y.4、y.5)。这些家伙的索引从 1 到 3,但是当您的 j 等于 3(度数)时,然后在
df$Cubic[i] = df$Cubic[i] + y.3[j + 1] * i ^ j中,您正在索引 y.3[4],这将为您提供 NA。我认为与其他 y 相同。 -
@din 感谢您的评论,我很难看到您在解释什么,但我终于明白了 - 我的错误是在 y.3、y.4、y.5 的生成中。被调用的索引不存在。感谢您指出这一点。
标签: r function loops while-loop