[R] matrix indices
Prof Brian D Ripley
ripley at stats.ox.ac.uk
Thu Jul 15 12:21:28 CEST 1999
On Thu, 15 Jul 1999, KAREN KOTSCHY wrote:
> Hi
>
> Could somebody please explain the following to me:
> If x is a 10x10 matrix,
> typing x[3] prints all 10 values of column 3, although the length of
> the vector =1. Why?
> x[,3] and x[[3]] both give all 10 values of column 3, length=10.
> What is the difference between these two, actually?
I suspect that x is actually a data frame in your application, as matrices
do not behave that way:
> x <- matrix(1:100, 10, 10)
> x[3]
[1] 3
> x[[3]]
[1] 3
> x[, 3]
[1] 21 22 23 24 25 26 27 28 29 30
> x <- as.data.frame(x)
> x[[3]]
[1] 21 22 23 24 25 26 27 28 29 30
> x[3]
V3
1 21
2 22
3 23
4 24
5 25
6 26
7 27
8 28
9 29
10 30
> length(x[3])
[1] 1
The reason is that a data frame is a list of columns: x[3] is a data frame
consisting of just one column: x[[3]] and x[, 3] give that column (as a
vector). You get length 1 as the length of the list.
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272860 (secr)
Oxford OX1 3TG, UK Fax: +44 1865 272595
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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