Skip to content

reexpand a matrix after subsetting

3 messages · Ido M. Tamir, Duncan Murdoch, Adaikalavan Ramasamy

#
Hi,

suppose I have a matrix (or dataframe) 
as a result from subsetting.

mat <- matrix(1:20,ncol=2)
mat[c(3,6,9),] <- NA
cc <- complete.cases(mat)
sub <- mat[cc,,drop=FALSE]
sub <- sub * 2
#some caluculations with sub.

now I would like to expand sub somehow
so row 3,6, and 9 would be filled with 
NAs but the rest should be in place again.
Is there a simple function for this?

merge is not an option.

Thank you very much for your help.

Ido


      [,1] [,2]
 [1,]    2   22
 [2,]    4   24
 [3,]   NA   NA
 [4,]    8   28
 [5,]   10   30
 [6,]   NA   NA
 [7,]   14   34
 [8,]   16   36
 [9,]   NA   NA
[10,]   20   40
#
On 8/29/2005 12:11 PM, Ido M. Tamir wrote:
You just need to calculate the original row numbers.  For example,

goodrows <- (1:nrow(mat))[cc]
mat[goodrows,,drop=FALSE] <- sub

Duncan Murdoch
1 day later
#
1) Do you really need to turn rows 3, 6, 9 of mat into NA ? I would
suggest the use of usediff() to remove them after complete.cases

2) The trick is to create a matrix of the same dimension as 'mat' but
initialised with NAs followed by replacing the required rows.

Example :

   w <- which( complete.cases(mat) )
   w <- setdiff( w, c(3,6,9) )
 
   out <- matrix( NA, nr=nrow(mat), nc=ncol(mat) )
   out[ w, ] <- 2 * mat[ w, ]

Regards, Adai
On Mon, 2005-08-29 at 18:11 +0200, Ido M. Tamir wrote: