如何只打印 lm 的系数?

how to print just coefficients of lm?

如果我有一行数据,y,像这样:

 1 4 5 6 3 4 

我可以使用以下代码找到拟合平滑曲线:

y <- scan(text = '1 4 5 6 3 4 ')
x <- seq_along(y)
fit <- lm(y ~ poly(x,5))

summary(fit)   
newy <- predict(fit, data.frame(x))

plot(y, type = "b")
lines(x, newy, col = "red") 

我需要对 600 行执行相同的操作并使用 summary(fit) 来获取系数。我的问题是我必须在其他软件中使用这些系数,我只需要系数,不需要额外的信息。有没有办法只打印出系数?

只是coef(fit)coef() 方法适用于 R 中的大多数统计模型:model$coefficients 适用于 lm 对象,但通常不可靠。 coef(summary(model))summary(model)$coefficients给出全系数table。 (coef()stats:::coef.default() 的默认方法使用 $coefficients 从对象中提取这些值,但其他模型对象的工作方式可能不同。)

如果我对你的问题的理解正确,你只需要没有附加任何描述符的数字。这是:

y <- scan(text = '1 4 5 6 3 4 ')
x <- seq_along(y)
fit <- lm(y ~ poly(x,5))

z <- coef(fit)
names(z) <- NULL
z

[1]  3.833333  1.553797 -2.836833  1.341641  1.133893  1.133893

请记住第一项是 y-intercept。