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

Berend Hasselman bhh at xs4all.nl
Thu Aug 15 16:30:32 CEST 2013


On 15-08-2013, at 09:29, Zhang Weiwu <zhangweiwu at realss.com> wrote:

> 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?

See the examples in ?`[` (seventh one).

n[1,,drop=FALSE]

Berend



More information about the R-help mailing list