[R] class "matrix" lost when extracting a row from matrix

Tobias Verbeke tobias.verbeke at openanalytics.eu
Sun Sep 19 10:16:09 CEST 2010


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



More information about the R-help mailing list