[R] if() for() { }

Marc Schwartz marc_schwartz at comcast.net
Fri Feb 16 17:38:31 CET 2007


On Fri, 2007-02-16 at 17:10 +0100, Nicolas Degallier wrote:
> Dear R'helpers,
> 
> I guess the solution is trivial but despite some hours of testing and  
> looking at the doc, I was unable to fix the following problem.
> 
> I want to do either:
> 
> for (i in 1:lat) a[i,which(a[i,]==0] <- NA
> 
> or:
> for (i in 1:lat) a[i,which(a[i,]==-9999|a[i,]==9999|a[i,]==9998|a[i,] 
> ==-9998)] <- NA

I may be missing something with respect to the structure of 'a'. It
would help to know if 'a' is a matrix (seems so).

In either case, the following may work:

  is.na(a) <- (abs(a) >= 9998) | (a == 0)

a <- sample(c(-9999, 9999, -9998, 9998, 0, 1:10))


> a
 [1]     0 -9998     8     7  9999     5    10     2 -9999     1  9998
[12]     6     9     3     4


is.na(a) <- (abs(a) >= 9998) | (a == 0)


> a
 [1] NA NA  8  7 NA  5 10  2 NA  1 NA  6  9  3  4


See ?is.na for more information


> if the word "Time" is or is not present in variable "nomfichier":
> test<-grep("Time",nomfichier)
> 
> the controlling test would be:
> 
> if (test==1)
> 
> But in either cases I obtain:
> 
> if (grep("Time",nomfichier)>0) for (i in 1:lat) a[i,which(a[i,]==0]  
> <- NA
> Erreur : syntax error
> 
>  > if (grep("Time",nomfichier)<>0) {for (i in 1:lat) a[i,which(a[i,] 
> ==-9999|a[i,]==9999|a[i,]==9998|a[i,]==-9998)] <- NA}
> Erreur : syntax error
>  >
> 
> I would appreciate if someone can show me the right way to do this.
> 
> Sincerely
> Nicolas


The above is also a bit confusing, but let me offer some insight into
grep().

If the value is present, then grep() returns the index of the matching
value (or the value itself, if "value = TRUE').

If the value is not present, then a 0 length integer or character
(depending upon whether 'value' is FALSE or TRUE) is returned.

Using the example from ?grep:

> txt <- c("arm","foot","lefroo", "bafoobar")

> grep("foo", txt)
[1] 2 4

> grep("foo", txt, value = TRUE)
[1] "foot"     "bafoobar"


However, if the expression is not matched:

> grep("MISS", txt)
integer(0)

> grep("MISS", txt, value = TRUE)
character(0)


Depending upon what you need to do, you can use any() for a simple
boolean result:

> any(grep("foo", txt))
[1] TRUE

> any(grep("MISS", txt))
[1] FALSE

This could provide an initial filter test to see if the value you
require is present in the target vector and if so, then get the actual
indices or values in a subsequent call to grep() if needed.

In other words, your initial 'if' statement and subsequent code may need
to be:

  if (any(grep("Time", nomfichier)))
  {
     is.na(a) <- (abs(a) >= 9998) | (a == 0)
  }


HTH,

Marc Schwartz



More information about the R-help mailing list