【问题标题】:R how to make lm() to reappear the curve formulaR如何让lm()重新出现曲线公式
【发布时间】:2022-09-29 12:09:08
【问题描述】:

我使用公式y=x^3+3 生成带有变量x 和y 的data.frame df, 但是当我使用lm() 来描述xy 的关系时,我得到y=81450x-5463207.2。这与原来的y=x^3+3 完全不同。 如何制作 lm() 或使用其他方式重新出现原始公式?

library(tidyverse)
mf <- function(x){
  y=x^3+3
}

df=data.frame()
for (i in 1:300){
  df[i,1]=i
  df[i,2]=mf(i)
}
names(df) <- c(\'x\',\'y\')


model <- lm(y~x,data = df)
model$coefficients
  • 您必须指定三次关系,即model &lt;- lm(y ~ I(x^3), data = df),模型会告诉您两个系数都是 3 和 1。
  • 谢谢,I(x^3) 可以重新出现原来的公式,但是如果我不知道原来的公式,我怎么知道应该输入 I(x^3) ? (我只想描述给定的趋势)
  • 有趣的是model &lt;- lm(y ~ poly(x, 5),data = df); round(model$coefficients, 2) 找不到正确的解决方案???
  • @Bernhard,那是因为您使用不同的基础指定了多项式。请改用model &lt;- lm(y ~ poly(x, 5, raw=TRUE),data = df)
  • @user2554330 注意我未来的自己:RTFM!谢谢你。

标签: r tidyverse lm


【解决方案1】:

@DarrenTsai 在 cmets 中首先回答,如果他也写了答案,请考虑先接受他的答案。

lm(y ~ x, data = df) 以 y = b0 + b1*x 的形式搜索解决方案,这不是数据的生成方式。您可以使用 I() 告诉 lm 包括 x^n,如

lm(y ~ x + I(x^2), + I(x^3) + I(x^4))

x + I(x^2), + I(x^3) + ... + I(x^n) 的缩写形式是 user2554330 的评论中使用的 `poly(x, n)'

让我对您的代码进行一些更改以获得更好的编码风格

# library(tidyverse)  -- you did not use any of this so there is no need to load it
mf <- function(x){ #  -- writing this in one without curly braces is an option 
  y=x^3+3          #  -- this will be retrieved as Intercept 3 plus 1*x^3
}


#for (i in 1:300){ -- there is really no need for a loop here
#  df[i,1]=i
#  df[i,2]=mf(i)
#}
#names(df) <- c('x','y')

df <- data.frame(x = 1:300,   #-- this is shorter and faster then the loop
                 y = mf(1:300))

model <- lm(y ~ poly(x, 5, raw = TRUE), data = df)
round(coef(model), 4)
#>             (Intercept) poly(x, 5, raw = TRUE)1 
#>                       3                       0 
#> poly(x, 5, raw = TRUE)2 poly(x, 5, raw = TRUE)3 
#>                       0                       1 
#> poly(x, 5, raw = TRUE)4 poly(x, 5, raw = TRUE)5 
#>                       0                       0

创建于 2022-09-24,reprex v2.0.2

(Intercept) 是三,这里编码为 poly(df$x, 5, raw = TRUE)3I(x^3) 是在 mf 中编码的一。

【讨论】:

    猜你喜欢
    • 2020-03-04
    • 2018-08-04
    • 1970-01-01
    • 2023-03-06
    • 2019-05-18
    • 2020-10-03
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    相关资源
    最近更新 更多