【问题标题】:LINEST function analogue for RR的LINEST函数模拟
【发布时间】:2026-01-20 07:00:02
【问题描述】:

我是 R 新手,正在尝试使用它。我需要获得与 R 等效的 LINEST 函数。

我可以从 Google 获得很多最小二乘的 URL,但我无法获得具有恒定值的 URL。我想将它用于方差分析。

例如,我想使用那些数组。第一个是y,其他是虚拟变量。

y = c(42,37,41,39,43,41,37,40,39,38,41,32,28,34,32,30,33)

x1 = c(1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0)

x2 = c(0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0)

x3 = c(0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1)

如果是LINEST,我可以使用LINEST(Y1:YN,X11:X3N,TRUE)得到结果。

附:在这种情况下,我应该得到如下结果:

在这种情况下,我应该得到如下结果:

|乙| C |常量 |

| -9 | -1 | 40.5 |

| 1.16 | 1.22 | 0.82 |

| 0.83 | 2.01 | |

| 33.74 | 14 |

| 274.76 | 57 |

【问题讨论】:

  • 您应该在这里告诉我们结果是什么,这样我们就可以确定我们在答案中得到了正确的结果。虽然这是我们在这里讨论的 Excel,但计算结果很少是正确的。
  • 哦,对不起。我很想,但我做不到,因为我不擅长编写 Markdown 语言。
  • 肯定只是 Excel 中的几个数字吗?在 Excel 中复制文本,编辑您的问题,粘贴文本,选择它,然后点击 {} 按钮将其标记为代码。就像我刚刚为您的数据示例所做的那样。
  • 嘿Spacedman!当然 LINEST 函数只返回 12 个值。我补充说。 (用笨拙的介绍。)

标签: r excel


【解决方案1】:

我相信您正在寻找summary(lm(y~x1+x2+x3)),如果知道这被称为“线性回归”,那么在 Google 上应该很容易找到。但是,您甚至不需要手动进行虚拟编码。只需使用 factor 变量,让 R 为您完成。

summary(lm(y~x1+x2+x3))

#Call:
#lm(formula = y ~ x1 + x2 + x3)
#
#Residuals:
#   Min     1Q Median     3Q    Max 
#  -3.5   -1.5    0.5    1.5    2.5 
#
#Coefficients: (1 not defined because of singularities)
#            Estimate Std. Error t value Pr(>|t|)    
#(Intercept)  31.5000     0.8238  38.240 1.45e-15 ***
#x1            9.0000     1.1650   7.726 2.05e-06 ***
#x2            7.5000     1.2218   6.138 2.57e-05 ***
#x3                NA         NA      NA       NA    
#---
#Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
# 
#Residual standard error: 2.018 on 14 degrees of freedom
#Multiple R-squared:  0.8282,   Adjusted R-squared:  0.8036 
#F-statistic: 33.74 on 2 and 14 DF,  p-value: 4.419e-06

NA 值之所以存在,是因为我们在模型中有一个截距,并且系统的等级不足以估计四个参数。您可以使用summary(lm(y~x1+x2+x3-1)) 排除拦截,但不建议这样做。

下面是使用因子变量的方法:

x <- factor(c(1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,3))
summary(lm(y~x))

#Call:
#lm(formula = y ~ x)
#
#Residuals:
#   Min     1Q Median     3Q    Max 
#  -3.5   -1.5    0.5    1.5    2.5 
#
#Coefficients:
#            Estimate Std. Error t value Pr(>|t|)    
#(Intercept)  40.5000     0.8238  49.165  < 2e-16 ***
#x2           -1.5000     1.2218  -1.228     0.24    
#x3           -9.0000     1.1650  -7.726 2.05e-06 ***
#---
#Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#
#Residual standard error: 2.018 on 14 degrees of freedom
#Multiple R-squared:  0.8282,   Adjusted R-squared:  0.8036 
#F-statistic: 33.74 on 2 and 14 DF,  p-value: 4.419e-06

注意现在截距是x1 的平均值,其他系数与这个平均值进行比较。

【讨论】:

  • 这正是我想要找到的。再次感谢罗兰先生。此外,这种方法比 Excel 中的方法提供的信息要多得多——例如 p 值。