At 15:31 07/09/01 -0400, Thomas Vogels <tov at ece.cmu.edu> wrote:
Hello. I'm afraid that I'm missing something very obvious this afternoon... When I add a column to a data.frame (by assigning to a "new" column name a logical vector), I thought that I had (at least) 3 options to do so: R> j <- data.frame (x=1:2) R> j$y <- c(TRUE,FALSE) #assignment 1 R> str(j) `data.frame': 2 obs. of 2 variables: $ x: int 1 2 $ y: logi TRUE FALSE R> j[["y"]] <- c(TRUE,FALSE) #assignment 2 R> str(j) `data.frame': 2 obs. of 2 variables: $ x: int 1 2 $ y: Factor w/ 2 levels "FALSE","TRUE": 2 1 R> j[["y"]] <- I(c(TRUE,FALSE)) #assignment 3 R> str(j) `data.frame': 2 obs. of 2 variables: $ x: int 1 2 $ y:Class 'AsIs' logi [1:2] TRUE FALSE Why is assignment 1 not identical to either assignment 2 or 3? Is there a method dispatch skipped? Thanks! -tom
Hi, I think that if you use names for indexing, you have to use single brackets ["..."], not double as in your example:
j <- data.frame (x=1:2) j["y"] <- c(TRUE,FALSE) #assignment 4 str(j)
`data.frame': 2 obs. of 2 variables: $ x: int 1 2 $ y: logi TRUE FALSE You'll need a more expert opinion than mine to explain the differences between [ and [[, but look at the following:
x <- 1:9 names(x) <- LETTERS[x] # give names to the observations x
A B C D E F G H I 1 2 3 4 5 6 7 8 9
x["C"]
C 3
x[["C"]]
[1] 3
names(x["C"])
[1] "C"
names(x[["C"]])
NULL The same with numeric indexing, but not logical indexing:
x[3]
C 3
x[[3]]
[1] 3
x[x == 3]
C 3
x[[x == 3]]
Error: attempt to select more than one element
Emmanuel Paradis
Laboratoire de Pal?ontologie
Institut des Sciences de l'?volution
Universit? Montpellier II
F-34095 Montpellier c?dex 05
France
phone: +33 4 67 14 39 64
fax: +33 4 67 14 36 10
mailto:paradis at isem.univ-montp2.fr
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._