[R] [] vs [[]]

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Fri Oct 20 12:10:26 CEST 2000


Bill Simpson <wsi at gcal.ac.uk> writes:

> > x<-1:10
> > x[4]
> [1] 4
> > x[[4]]
> [1] 4
> doesn't seem to matter if you use [] or [[]]

Only when names are not involved:

> x[4]
d 
4 
> x[[4]]
[1] 4


> List
> > x<-list(1,2,3,4)
> > x[2]
> [[1]]
> [1] 2
> 
> > x[[2]]
> [1] 2
> doesn't seem to matter if you use [] or [[]]

Look closer. In the first case you got a list. In general, [[ gives
you the "most primitive" result, whereas [ gives you something that is
"like the original". Note also that [[ does not allow complex
indexing: if

x <- list(a=1, b=1:2, c=letters[1:3])

then x[2:3] makes sense, but x[[2:3]] does not (and doesn't work
either). 
 
> This question started from nls(). If you do
> fit<-nls(...)
> using a 2 param model
> > coef(fit)
>           a           b 
> 212.6836297   0.0641211 
> > coef(fit)[1]
>        a 
> 212.6836 
> > coef(fit)[[1]]
> [1] 212.6836
> 
> I guess coef(fit) returns some weird sort of list and so I need
> coef(fit)[[]] to get the fitted parameters.

No, this is just the name-dropping (sorry..) effect of [[, coef(fit)
is just an ordinary named numeric vector.

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list