[R] reduce the code used by "for"

Luis Ridao Cruz Luisr at frs.fo
Tue Dec 4 12:40:58 CET 2007


R-help,

I have a 3-way array:

> dim(bugvinP)
[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

> version
               _                           
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)
>



More information about the R-help mailing list