R how to make lm() to reappear the curve formula

Viewed 27

I use formula y=x^3+3 to generate data.frame df with variables x and y, but when i using lm() to describe the relation of xy, i get y=81450x-5463207.2. This is really different with the original y=x^3+3. How to make lm() or using other way to reappear the original formula ?

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
1 Answers

@DarrenTsai ansered first in the comments, if he also writes an answer, consider to accept his' first.

lm(y ~ x, data = df) searches for a solution in the form of y = b0 + b1*x which is not how the data were generated. You can tell lm to include x^n using I() as in

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

a short form for x + I(x^2), + I(x^3) + ... + I(x^n) is `poly(x, n)' as used in the comment of user2554330

Let me do some changes of your code for better coding style

# 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(df$x, 5, raw=TRUE),data = df)
round(model$coefficients, 4)
#>                (Intercept) poly(df$x, 5, raw = TRUE)1 
#>                          3                          0 
#> poly(df$x, 5, raw = TRUE)2 poly(df$x, 5, raw = TRUE)3 
#>                          0                          1 
#> poly(df$x, 5, raw = TRUE)4 poly(df$x, 5, raw = TRUE)5 
#>                          0                          0

Created on 2022-09-24 with reprex v2.0.2

(Intercept) is three and the I(x^3) coded here as poly(df$x, 5, raw = TRUE)3 is one as coded in mf.

Related