[R] Simple question on replace a matrix row

William Dunlap wdunlap at tibco.com
Fri Jan 29 23:58:02 CET 2010



Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com  

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of anna
> Sent: Friday, January 29, 2010 2:46 PM
> To: r-help at r-project.org
> Subject: Re: [R] Simple question on replace a matrix row
> 
> 
> What I did now is that I checked the class of both matrix 
> before assigning
> the first row of mat2:
> class(mainMat) --> "matrix"
> class(mainMat[1,]) --> "list"
> class(mat2) --> "matrix"
> mat2[1,]<-mainMat[1,]
> class(mat2) --> "list"
>  I think the problem comes from mainMat[1,] that should be of 
> class "matrix"
> but is of class "list"...

You need to look further into the structure of
those objects to see what is going on.  A matrix
can contain data of any simple enough (vector-like)
class, e.g., "numeric", "integer", "list", or "logical".
The class of the matrix is always "matrix", no matter
what is in it.  A "matrix" can be subscripted with 2
subscripts and contains one vector of data, in column
major order, of length nrow(matrix)*ncol(matrix).
(A "data.frame" is another 2 dimensional object with
a quite different structure and significantly different
behavior.)

I'd recommend using str() to get a fuller picture:

  > matList<-matrix(lapply(1:4,seq_len), 2, 2)
  > matNumeric<-matrix(exp(0:3), 2, 2)
  > class(matList)
  [1] "matrix"
  > class(matNumeric)
  [1] "matrix"
  > str(matList)
  List of 4
   $ : int 1
   $ : int [1:2] 1 2
   $ : int [1:3] 1 2 3
   $ : int [1:4] 1 2 3 4
   - attr(*, "dim")= int [1:2] 2 2
  > str(matNumeric)
   num [1:2, 1:2] 1 2.72 7.39 20.09 
 
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 

> Anna Lippel
> -- 
> View this message in context: 
> http://n4.nabble.com/Simple-question-on-replace-a-matrix-row-t
p1427857p1437234.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 



More information about the R-help mailing list