[R] How to refer the element in a named list?

Duncan Murdoch murdoch at stats.uwo.ca
Sun Sep 6 19:35:43 CEST 2009


On 06/09/2009 1:04 PM, Peng Yu wrote:
> Hi,
> 
> I thought that 'coefficients' is a named list, but I can not refer to
> its element by something like r$coefficients$y. I used str() to check
> r. It says the following. Can somebody let me know what it means?

The line that matters is the one

  $ coefficients : Named num [1:2] 1.12e-15 1.00

It says that coefficients is a numeric ("num") vector, not a list.  So 
r$coefficients["y"] will extract the y coefficient.

Duncan Murdoch


>   ..- attr(*, "names")= chr [1:2] "(Intercept)" "y"
> 
> $ Rscript lm.R
>> x=1:10
>> y=1:10
>> r=lm(x~y)
>> class(r)
> [1] "lm"
>> mode(r)
> [1] "list"
>> r
> 
> Call:
> lm(formula = x ~ y)
> 
> Coefficients:
> (Intercept)            y
>   1.123e-15    1.000e+00
> 
>> r$coefficients[1]
>  (Intercept)
> 1.123467e-15
>> r$coefficients[[1]]
> [1] 1.123467e-15
>> r$coefficients[2]
> y
> 1
>> r$coefficients[[2]]
> [1] 1
> 
> 
>> str(r)
> List of 12
>  $ coefficients : Named num [1:2] 1.12e-15 1.00
>   ..- attr(*, "names")= chr [1:2] "(Intercept)" "y"
> 
> Regards,
> Peng
> 
> ______________________________________________
> 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.




More information about the R-help mailing list