VBA迭代回归

时间:2019-01-10 14:37:47

标签: excel vba

我正在编写一个代码,以对来自更大数据集的用户定义的数据点集执行迭代回归分析。输出是R ^ 2值,其中我的代码的另一部分将获取最大值,以及该值出现的索引。我在迭代回归序列中遇到的问题之一是,该循环仅适用于某些“ sample_count”值,具体取决于输入数据的长度。感谢您的帮助,因为我已经凝视了一段时间。

Lastrow = Range("G" & Rows.Count).End(xlUp).Row
Range("I2:I" & Lastrow).Formula = "=$B$1*(G2/60)"
Range("J2:J" & Lastrow).Formula = "=($B$2*0.002)+I2"

sample_count = Application.InputBox("Please Enter       Number of Data Points to Consider for Linearity", , Type:=1)
Set r = Range("E2")
N = Range(r, r.End(xlDown)).Rows.Count
i = 0: j = 0

Do While i + 2 * sample_count < N
Set rX = r.Offset(i, 4).Resize(sample_count, 1)
Set ry = r.Offset(i, 0).Resize(sample_count, 1)
rsquare = Application.WorksheetFunction.RSq(ry, rX)
r.Offset(j, 7).Value = rsquare
i = i + sample_count
j = j + 1
Loop

2 个答案:

答案 0 :(得分:0)

尝试在循环外设置原始范围,然后就可以在循环内偏移。

我不确定是否还有其他问题。

declare your variables是一个好习惯。

Set rX = r.Offset(, 4).Resize(sample_count, 1) 'H3:H52
Set rY = r.Resize(sample_count, 1)

Do While i + 2 * sample_count < N
    rsquare = Application.WorksheetFunction.RSq(rY, rX)
    r.Offset(j, 7).Value = rsquare
    i = i + sample_count
    j = j + 1
    Set rX = rX.Offset(sample_count)
    Set rY = rY.Offset(sample_count)
Loop

答案 1 :(得分:0)

我相信导致问题的原因是您迭代的方式。例如,如果我采用参数N = 32并且我的sample_count为8并使用

分析循环
Do While i + 2 * sample_count < N
    i = i + sample_count
    j = j + 1
    Debug.Print "@ iteration " & j & " i = " & i & vbCrLf; "i + 2 * sample_count = " & i + 2 * sample_count & " < " & N
Loop 

我知道

iteration 1 i = 8  
i + 2 * sample_count = 24 < 32  
iteration 2 i = 16  
i + 2 * sample_count = 32 < 32

所以我只有4个样本组中的2个。话虽这么说,假设您想通过sample_count.Offset进行偏移,我认为您可以通过将“ Do While-Loop”替换为“

”来有效地实现所需的功能
For i = 0 To N Step sample_count
    Set rX = r.Offset(i, 4).Resize(sample_count, 1)
    Set ry = r.Offset(i, 0).Resize(sample_count, 1)
    rsquare = Application.WorksheetFunction.RSq(ry, rX)
    r.Offset(i + sample_count, 7).Value = rsquare
End Sub