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

Duncan Murdoch murdoch at stats.uwo.ca
Sun Sep 6 23:01:17 CEST 2009


On 06/09/2009 1:45 PM, David Winsemius wrote:
> On Sep 6, 2009, at 1:35 PM, Duncan Murdoch wrote:
> 
>> 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.
>>
> 
> And r$coefficients[`(Intercept)`] # note back-quote, should get you  
> the intercept

No, that says to get the element of the coefficients whose index is 
stored in a variable named `(Intercept)`.  (Chances are that variable 
doesn't exist, unless you made an effort to create it.  And if you 
perversely stored "y" in it you'd get the same coefficient as before!)

You want regular (single or double, R doesn't care) quotes to say that 
you are giving the index directly:

r$coefficients["(Intercept)"]

Duncan Murdoch
> 
> ?coef
> 
> Generally coef(fit) will extract model coefficients across a wider  
> range of R model objects.
> 
> 
>> 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.
>> ______________________________________________
>> 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, MD
> Heritage Laboratories
> West Hartford, CT




More information about the R-help mailing list