[R] Removing description from lm()

David Winsemius dwinsemius at comcast.net
Mon Oct 6 19:54:37 CEST 2014


On Oct 5, 2014, at 6:50 PM, billy am wrote:

> Hi David , 
> 
> coef alone won't do as it still contains the description.

It's not a "description", ; in R parlance it's a "name" although that parlance can be confused since there is also a language class called "name". In this case it's an attribute with the name "names". This is a rather special attribute since R gives you a function for setting and removing the "names" attribute.

?'names<-'


> attributes(coef(lm(c(1:3, 7, 6) ~ x))[1])
$names
[1] "(Intercept)"


> As per the example in ?coef shows ,
> 
> > 
> x <- 1:5; coef(lm(c(1:3, 7, 6) ~ x))
> 
> (Intercept)           x 
>        -0.7         1.5 
> 
> 
> 
> Unless I use cat again , 
> 
> > 
> x <- 1:5; cat(coef(lm(c(1:3, 7, 6) ~ x))[1])
> 
> -0.7
> 

You may be confused about what is happening. The other respondents suggested using `unname` because that function would return a value stripped of the attribute. The `cat` function does not actually return a value; it only creates a side-effect at the console or output to a file:

xcf <- cat(coef(lm(c(1:3, 7, 6) ~ x))[1])
-0.7
> xcf
NULL

So `unname` would be preferable if you were trying to store that value.

-- 
David

> Thanks!
> Billy
> 
> 
> 
> On Mon, Oct 6, 2014 at 8:42 AM, David Winsemius <dwinsemius at comcast.net> wrote:
> ?coef
> 
> Sent from my iPhone
> 
> > On Oct 5, 2014, at 4:21 AM, billy am <wickedpuppy at gmail.com> wrote:
> >
> > Hi ,
> >
> > When I run the following code , I get both the description and the value ,
> > eg : Intercept and 0.5714286.
> >
> > Is there a way to extract just the value 0.5714286? Thanks!
> >
> >
> >> x <- c(1,5,3,1)> y <- c(5,8,2,3)> lm(x~y)
> > Call:
> > lm(formula = x ~ y)
> >
> > Coefficients:
> > (Intercept)            y
> >     0.5714       0.4286
> >> lm(x~y)$coefficient[1](Intercept)
> >  0.5714286
> >
> >
> >>
> >
> > Regards
> > Billy
> >
> >    [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > R-help at r-project.org mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
> 

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list