[R] keeping dim() for array

Gavin Simpson gavin.simpson at ucl.ac.uk
Tue Nov 21 13:44:28 CET 2006


On Tue, 2006-11-21 at 12:20 +0000, Federico Calboli wrote:
> Hi All,
> 
> I noticed the following:
> 
> pip = array(1:6, dim = c(3,2))
> dim(pip)
> [1] 3 2
> 
> pup = pip[1,]
> dim(pup)
> NULL
> 
> I bet there is a *good* reason why one row of an array is *dimensionless*, but 
> it's highly inconvenient for my purpose, i.e. to use apply() after an array goes 
> through a number of logical steps and is redimensioned, sometimes to one single row.

When you subset a dimensioned object in R, the default is for the empty
dimension to be dropped - in your case converting your 1, row matrix
into a vector of the same length.

I do not know /why/ this is so, but I find it quite useful when writing
code - although I've been bitten by this enough times now to remember to
add drop = FALSE.

> 
> How do I keep dim(pup) to 1 2?

pup <- pip[1, , drop = FALSE]

will stop the empty dimension being dropped:

> pip = array(1:6, dim = c(3,2))
> pup <- pip[1, , drop = FALSE]
> pup
     [,1] [,2]
[1,]    1    4
> dim(pup)
[1] 1 2

> 
> Since pup is at the end of a number of if(), it does not necessarily end up as 
> one row only, so t(as.matrix(pup)) is the *wrong* answer.
> 
> Best,
> 
> Federico

HTH

G
-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Gavin Simpson                 [t] +44 (0)20 7679 0522
 ECRC & ENSIS, UCL Geography,  [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%



More information about the R-help mailing list