[R] Confusing concept of vector and matrix in R
Stu
stu.andrews at gmail.com
Mon Apr 26 23:20:57 CEST 2010
Hi all,
One subtlety is that the drop argument only works if you specify 2 or
more indices e.g. [i, j, ..., drop=F]; but not for a single index e.g
[i, drop=F].
Why doesn't R complain about the unused "drop=F" argument in the
single index case?
Cheers,
- Stu
a = matrix(1:10, nrow=1)
b = matrix(10:1, ncol=1)
# a1 is an vector w/o dim attribute (i.e. drop=F is ignored silently)
(a1 = a[2:5, drop=F])
dim(a1)
# a2 is an vector WITH dim attribute: a row matrix (drop=F works)
(a2 = a[, 2:5, drop=F])
dim(a2)
# b1 is an vector w/o dim attribute (i.e. drop=F is ignored silently)
(b1 = b[2:5, drop=F])
dim(b1)
# b2 is an vector WITH dim attribute: a column matrix (drop=F works)
(b2 = b[2:5, , drop=F])
dim(b2)
On Mar 30, 4:08 pm, lith <minil... at gmail.com> wrote:
> > Reframe the problem. Rethink why you need to keep dimensions. I never ever had to use drop.
>
> The problem is that the type of the return value changes if you happen
> to forget to use drop = FALSE, which can easily turn into a nightmare:
>
> m <-matrix(1:20, ncol=4)
> for (i in seq(3, 1, -1)) {
> print(class(m[1:i, ]))}
>
> [1] "matrix"
> [1] "matrix"
> [1] "integer"
>
> ______________________________________________
> R-h... at r-project.org mailing listhttps://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guidehttp://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list