日期如下所示
enter image description here
我想计算每个组的系数并填充相干单元(D&E列)
我可以在R中使用subset()进行操作,并在每个子集中进行计算。
我的R代码在
以下for (row in 1:nrow(alpha.beta.d)){
train.d <- subset(analysis.d, tic == alpha.beta.d$tic[row])
if (nrow(train.d) == 0) {next}
linear.regression <- lm(y ~ x, data = train.d)
a <- linear.regression$coefficients[1]
b <- linear.regression$coefficients[2]
alpha.beta.d[row, "constant"] <- a
alpha.beta.d[row, "coefficient"] <- b
}
但是我在VBA中找不到subset()或类似的命令。
我尝试使用2 for循环,但是数据太多。
如何使用VBA进行操作?
还是我不需要VBA,我可以在excel中做同样的事情?
答案 0 :(得分:0)
我不了解R,因此我无法确切地说出您要做什么,但是Excel具有多种用于回归分析的功能。
SLOPE()
函数将为您提供斜率 b (我认为这是“系数”的意思),而INTERCEPT()
函数将为您提供y-拦截 a (我认为这是您所说的“常量”的意思)。还有LINEST()
函数可以返回各种可能对您有用的统计信息(请参见https://support.office.com/en-us/article/linest-function-84d7d0d9-6e50-4101-977a-fa7abf772b6d)
直接在电子表格中输入的所有这些Excel函数中的任何一个都将返回您可能需要的值,而无需使用VBA。但是,下面是获取相同统计信息的VBA代码。这不是管理数据的最有效方法,但是我不确定您在Excel-VBA中的经验水平,因此我尝试使代码易于理解。您可能需要根据实际需要使用LinEst
结果,并且可以通过将最后一个参数更改为True
来绘制其他数据(请注意,返回数组将变为二维,因此您可以需要更改下面给出的常量):
Const COEFFICIENT_b As Long = 1
Const CONSTANT_a As Long = 2
Dim ws As Worksheet
Dim firstRow As Long, lastRow As Long, r As Long
Dim groupFirstRow As Long, groupLastRow As Long
Dim colGrp As Long, colX As Long, colY As Long, colB As Long, colA As Long
Dim groupID As Long
Dim rngX As Range, rngY As Range
Dim result As Variant
'Define range parameters
Set ws = ThisWorkbook.Worksheets("Sheet1") 'set this to your sheet object
firstRow = 2
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
colGrp = 1
colX = 2
colY = 3
colB = 4
colA = 5
'Set the group values to first item
groupID = ws.Cells(firstRow, colGrp).Value2
groupFirstRow = firstRow
For r = firstRow + 1 To lastRow
'Check for a new group.
If ws.Cells(r, colGrp).Value2 <> groupID Or r = lastRow Then
'Set the row limit for this group.
groupLastRow = IIf(r = lastRow, r, r - 1)
'Set the X and Y data ranges.
Set rngY = ws.Range(ws.Cells(groupFirstRow, colY), ws.Cells(groupLastRow, colY))
Set rngX = ws.Range(ws.Cells(groupFirstRow, colX), ws.Cells(groupLastRow, colX))
'Call the LinEst function.
result = WorksheetFunction.LinEst(rngY, rngX, True, False)
'Write the results to the sheet.
ws.Cells(groupFirstRow, colB) = result(COEFFICIENT_b)
ws.Cells(groupFirstRow, colA) = result(CONSTANT_a)
'Reset the groupId and row variables
groupID = ws.Cells(r, colGrp).Value2
groupFirstRow = r
End If
Next