Hi, I've got a quick question about what happens when indexing into matrices with a single column. I was wondering if anyone can help ... For example:> x <- matrix(1:10)> y <- cbind(x,x)> x[4:6,][1] 4 5 6> y[4:6,][,1] [,2] [1,] 4 4 [2,] 5 5 [3,] 6 6> class(x[4:6,])[1] "integer"> class(y[4:6,])[1] "matrix" It seems that R is returning the results of indexing into a matrix with one column as a vector rather than a matrix? Does anyone have a good way of preventing this from happening? cheers, crispin -------------------------------------------------------- This email is confidential and intended solely for the use o...{{dropped}}
There's an optional "drop" argument to the indexing operations, which is by default TRUE. You just want> x[4:6,,drop=FALSE][,1] [1,] 4 [2,] 5 [3,] 6 Reid Huntsinger -----Original Message----- From: r-help-bounces at stat.math.ethz.ch [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Crispin Miller Sent: Thursday, September 01, 2005 10:54 AM To: R-help at stat.math.ethz.ch Subject: [R] Matrices with a single column Hi, I've got a quick question about what happens when indexing into matrices with a single column. I was wondering if anyone can help ... For example:> x <- matrix(1:10)> y <- cbind(x,x)> x[4:6,][1] 4 5 6> y[4:6,][,1] [,2] [1,] 4 4 [2,] 5 5 [3,] 6 6> class(x[4:6,])[1] "integer"> class(y[4:6,])[1] "matrix" It seems that R is returning the results of indexing into a matrix with one column as a vector rather than a matrix? Does anyone have a good way of preventing this from happening? cheers, crispin -------------------------------------------------------- This email is confidential and intended solely for the use o...{{dropped}} ______________________________________________ R-help at stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Crispin Miller wrote:> Hi, > I've got a quick question about what happens when indexing into matrices > with a single column. I was wondering if anyone can help ... > > For example: > >>x <- matrix(1:10) > > >>y <- cbind(x,x) > > >>x[4:6,] > > > [1] 4 5 6 > > >>y[4:6,] > > > [,1] [,2] > > [1,] 4 4 > > [2,] 5 5 > > [3,] 6 6 > > >>class(x[4:6,]) > > > [1] "integer" > > >>class(y[4:6,]) > > > [1] "matrix" > > It seems that R is returning the results of indexing into a matrix with > one column as a vector rather than a matrix? > > Does anyone have a good way of preventing this from happening?Yes, the argument "drop": x[4:6,,drop=FALSE] Uwe Ligges> cheers, > > crispin > > -------------------------------------------------------- > > > This email is confidential and intended solely for the use o...{{dropped}} > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html