Skip to content

reduce the code used by "for"

2 messages · Luis Ridao Cruz, Domenico Vistocco

#
R-help,

I have a 3-way array:
[1] 13 14  3

The array looks something like this (object trimmed for readability)
, , slag = 1

    ar
      1994  1995  1996  1997  1998
  1     NA 0.000 0.000 0.000 0.000
  2  0.036 0.059 0.027 0.000 0.000
  3  0.276 0.475 0.491 0.510 0.559
  10 1.000 1.000 1.000 1.000 1.000
  11    NA 1.000 1.000    NA 1.000
  12    NA 1.000 1.000 1.000 1.000
  13    NA 1.000    NA 1.000    NA

, , slag = 2

    ar
      1994  1995  1996  1997  1998
  1     NA 0.000 0.000 0.000 0.000
  2  0.129 0.029 0.011 0.026 0.000
  9  1.000 1.000 1.000 1.000 1.000
  10 1.000 1.000 1.000 1.000 1.000
  11 1.000 1.000 1.000 1.000 1.000
  12 1.000 1.000 1.000 1.000 1.000
  13    NA    NA 1.000 1.000    NA


I want to set NAs to 0 if the row names are e.g. 3 
and 1 otherwise. To implement this I do the following which
is OK but I wish to find out a more compact/shorter version.

for(i in 1:3)
{
bugvinP[,,i] <- ifelse(as.numeric(rownames(bugvinP[,,i])) < 3 &
is.na(bugvinP[,,i]), 0
, ifelse(as.numeric(rownames(bugvinP[,,i])) > 9 & is.na(bugvinP[,,i]),
1, bugvinP))
}


Thanks in advance
_                           
platform       i386-pc-mingw32             
arch           i386                        
os             mingw32                     
system         i386, mingw32               
status                                     
major          2                           
minor          6.1                         
year           2007                        
month          11                          
day            26                          
svn rev        43537                       
language       R                           
version.string R version 2.6.1 (2007-11-26)
#
> y=array(rep(x,15),c(5,3,2))
 > dimnames(y)=list(1:5,letters[1:3],NULL)

So to have in the workspace:
 > y
, , 1
   a  b  c
1 10 50 40
2 20 10 50
3 NA 20 10
4 30 NA 20
5 40 30 NA

, , 2
   a  b  c
1 30 NA 20
2 40 30 NA
3 50 40 30
4 10 50 40
5 20 10 50

Then to set the missing in the third row to 0:
 > y[3,,][which(is.na(y[3,,]))]=0

and to set the missing in the other rows to 1:
 > y[-3,,][which(is.na(y[-3,,]))]=1

domenico vistocco
Luis Ridao Cruz wrote: