0

I have read some posts about extracting coefficient values from lm for example here

but I would like to have only the value of intercept and not the text. What should I do?

here you can see part of my simple code:

...
f<-lm(res[,1]~res[,2])
f
...
Community
  • 1
  • 1
Kaja
  • 2,962
  • 18
  • 63
  • 99
  • 1
    Try `unname(f[[1]][1])` – RHertel Jul 13 '16 at 11:40
  • 2
    haha 28 seconds faster :) – Sotos Jul 13 '16 at 11:40
  • Or slightly easier to remember, `unname(coef(f))`. – David_B Jul 13 '16 at 11:42
  • @RHertel that works :) could please tell me what does your code do? Why should we do that? whicht data structure has 'f'? – Kaja Jul 13 '16 at 11:42
  • If you look at `c(f)` you should be able to see how to access it's properties. – Akhil Nair Jul 13 '16 at 11:49
  • 4
    The structure of `f` can be inspected with `str(f)`. This shows that `f` is a list with 12 entries. The intercept is stored as one of the two values in the first entry of the list, `f[[1]]` or, equivalently, `f$coefficients`. That first entry of the list contains two named numerical values. The command `unname()`removes the name, and by using `f$coefficients[1]` it is specified that only the first value (the intercept) should be selected. Hope this helps. – RHertel Jul 13 '16 at 11:49

1 Answers1

4

If you want to use the data from the lm function, like the coefficients, p values, etc I suggest using the broom package.

Accessing the intercept can than be done using the function tidy. this will return a data.frame. Simple example:

library(broom)
f <- lm(speed ~ ., data = cars)
df1 <- tidy(f)

df1
         term  estimate  std.error statistic      p.value
1 (Intercept) 8.2839056 0.87438449  9.473985 1.440974e-12
2        dist 0.1655676 0.01749448  9.463990 1.489836e-12
phiver
  • 23,048
  • 14
  • 44
  • 56