[R] how to retain dimension when selecting one row from a matrix?

Zhang Weiwu zhangweiwu at realss.com
Thu Aug 15 09:29:35 CEST 2013


When you select a single row from a matrix, the dimsion is lost:

> n <- matrix(nrow = 3, ncol = 5)
> dim(n)
[1] 3 5
> dim(n[1,])
NULL
> dim(n[2,])
NULL

This doesn't happen if you select more than one row:

> dim(n[1:2,])
[1] 2 5

This is causing trouble. SCENARIO: when I filter out unqualified sampled 
data, I was not unaware that only one row of data qualifies, and the 
resulted selected data thus doesn't have dimension.  I would call matrix[,3] 
and get an error.

One way to mend this is to re-assign the dimension to the result set, but 
that destories column names...

> selected = n[1,]
> selected
unixtime     agio    count      ask      bid
       NA       NA       NA       NA       NA 
> dim(selected)
NULL
> dim(selected) <- c(1,5)
> selected
      [,1] [,2] [,3] [,4] [,5]
[1,]   NA   NA   NA   NA   NA

Is there a way to retain dimension when selecting only one row from a 
matrix?



More information about the R-help mailing list