gpt4 book ai didi

替换 [r] 中的 lm 系数

转载 作者:行者123 更新时间:2023-12-04 05:07:00 28 4
gpt4 key购买 nike

是否可以替换 lm 对象中的系数?

我认为以下会起作用

# sample data 
set.seed(2157010)
x1 <- 1998:2011
x2 <- x1 + rnorm(length(x1))
y <- 3*x1 + rnorm(length(x1))
fit <- lm( y ~ x1 + x2)

# view origional coefficeints
coef(fit)

# replace coefficent with new values
fit$coef(fit$coef[2:3]) <- c(5, 1)

# view new coefficents
coef(fit)

任何帮助将不胜感激

最佳答案

您的代码不可重现,因为您的代码中几乎没有错误。这是更正后的版本,它也显示了您的错误:

set.seed(2157010) #forgot set.
x1 <- 1998:2011
x2 <- x1 + rnorm(length(x1))
y <- 3*x2 + rnorm(length(x1)) #you had x, not x1 or x2
fit <- lm( y ~ x1 + x2)

# view original coefficients
coef(fit)
(Intercept) x1 x2
260.55645444 -0.04276353 2.91272272

# replace coefficients with new values, use whole name which is coefficients:
fit$coefficients[2:3] <- c(5, 1)

# view new coefficents
coef(fit)
(Intercept) x1 x2
260.5565 5.0000 1.0000

所以问题是你使用的是 fit$coef ,尽管 lm 中的组件名称输出真的是 coefficients .缩写版本适用于获取值,但不适用于设置,因为它创建了名为 coef 的新组件。 ,以及 coef函数提取了 fit$coefficient 的值.

关于替换 [r] 中的 lm 系数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15417680/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com