[R] $name vs. [["name"]]

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Fri Nov 16 15:31:05 CET 2001


Kjetil Kjernsmo <kjetil.kjernsmo at astro.uio.no> writes:

> Dear all,
> 
> I have been away for a month, but some time ago, I noted something that
> was very surprising to me. I think this example illustrates it well:
> > test <- data.frame(col1 = c(1,2), col2=c(3, 4))
> > test
>   col1 col2
> 1    1    3
> 2    2    4
> > apply(test, 1, function(x) browser())
> Called from: FUN(newX[, i], ...)
> Browse[1]> x$col1
> NULL
> Browse[1]> x[["col1"]]
> [1] 1
> Browse[1]> x[["col2"]]
> [1] 3
> Browse[1]> x$col2
> NULL
> 
> it seems like the $name notation and the [["name"]] notation are
> different, yet, what I understand from the intro, they should be
> identical.
> 
> What's the deal?

x is a vector at that stage and $ works on lists and data frames. Try

x <- 1:3 ; names(x)<-letters[1:3] ; x[["b"]] ; x$b

(Actually, I'm mildly surprised that x$b doesn't give an error...)

Even for data frames $ and [[ aren't quite the same since method
dispatch differs.

-- 
   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