hw at wiseadvice.eu
2010-Sep-19 08:02 UTC
[R] class "matrix" lost when extracting a row from matrix
Good morning experts! situation: class(myMatrix)="matrix" class(myMatrix[(1:2),]))="matrix" class(myMatrix[1,])= "character" consequences are far reaching as, for instance colnames(myMatrix[(1:2),]) != colnames(myMatrix[1,]) or names(myMatrix[(1:2),]) != names(myMatrix[1,]) My question: 1. How can the coercion to character be avoided and the attributes of the original object myMatrix of class "matrix" been preserved when slicing out one row of the matrix? 2. Is there a reason why there is a "loss of generality" in that sense that a matrix of dimension (1xn) is treated differently than a matrix of dimension (mxn); m,n>1 ? in other words is there a reason why class vector is needed at all? Many thanks for your help! Holger -- View this message in context: http://r.789695.n4.nabble.com/class-matrix-lost-when-extracting-a-row-from-matrix-tp2545719p2545719.html Sent from the R help mailing list archive at Nabble.com.
Tobias Verbeke
2010-Sep-19 08:16 UTC
[R] class "matrix" lost when extracting a row from matrix
On 09/19/2010 10:02 AM, hw at wiseadvice.eu wrote:> > Good morning experts! > > situation: > > class(myMatrix)="matrix" > class(myMatrix[(1:2),]))="matrix" > class(myMatrix[1,])= "character" > > consequences are far reaching as, for instance colnames(myMatrix[(1:2),]) !> colnames(myMatrix[1,]) or names(myMatrix[(1:2),]) != names(myMatrix[1,]) > > My question: > 1. How can the coercion to character be avoided and the attributes of the > original object myMatrix of class "matrix" been preserved when slicing out > one row of the matrix? > 2. Is there a reason why there is a "loss of generality" in that sense that > a matrix of dimension (1xn) is treated differently than a matrix of > dimension (mxn); m,n>1 ? in other words is there a reason why class vector > is needed at all?m <- matrix(1:4, 2) m[1,, drop = FALSE] # [,1] [,2] # [1,] 1 3 m[, 1, drop = FALSE] # [,1] # [1,] 1 # [2,] 2 See ?Extract HTH, Tobias