[R] adding logical vector to data frame
Thomas Vogels
tov at ece.cmu.edu
Mon Sep 10 21:08:53 CEST 2001
Prof Brian D Ripley <ripley at stats.ox.ac.uk> writes:
> R version?
>
> This works correctly in R-devel. Yes, using $ on data frame subverts some
> of the conversions, but logical variables are full-status variables now.
Prof. Ripley,
thanks for the answer--both parts (confirmation of different treatment
of '$' and news from R-devel) are very helpful.
Emmanuel Paradis <paradis at isem.univ-montp2.fr> writes:
[snip]
> 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
Quite obviously, I'm not an expert, but in my simple-minded view, []
subsets, while [[]] extracts (one element, and one element only).
So x["C"] is the third row of x while x[["C"]] gives you the
third element (a scalar, no name).
> 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
because 'x == 3' results in a vector of the same length as x. Since
that length is > 1, an error occurs. (You could argue that if the
index vector contains exactly one TRUE value, '[['() could proceed,
but that's probably more dangerous than helpful.)
-tom
--
mailto:tov at ece.cmu.edu (Tom Vogels) Tel: (412) 268-6638 FAX: -3204
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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