[R] if(){} else{}

Gavin Simpson gavin.simpson at ucl.ac.uk
Tue Dec 5 17:46:37 CET 2006


On Tue, 2006-12-05 at 16:33 +0100, Hans-Juergen Eickelmann wrote:
> Dear R-community,
> 
> my data set looks like 'mat' below.
> 
> Plant<-c(NA,1,1,1,NA,NA,NA,NA,NA,1);
> Value1<-rnorm(1:10);

You only really need rnorm(10), as in ?rnorm, rnorm is defined as
rnorm(n, mean=0, sd=1) and n is the number of observations.

> Value2<-rnorm(1:10);
> mat<-cbind(Plant,Value1,Value2);

You don't need the ";" at the ends of the lines, and cbind() returns a
matrix, for which you cannot use "$" to access the columns:

> class(mat)
[1] "matrix"
> mat$Plant
NULL

What you are looking for is ifelse(), see ?ifelse, but here is your
example, suitable spaced out and minus the other infelicities.

Plant <- c(NA, 1, 1, 1, NA, NA, NA, NA, NA, 1)
Value1 <- rnorm(10)
Value2 <- rnorm(10)
mat <- data.frame(Plant, Value1, Value2)
mat$Plant1 <- ifelse(is.na(mat$Plant), "A", "B")

> mat$Plant1
 [1] "A" "B" "B" "B" "A" "A" "A" "A" "A" "B"
> mat
   Plant      Value1      Value2 Plant1
1     NA  2.76603270 -0.20435729      A
2      1 -0.54688170 -0.81943566      B
3      1  0.30480812 -0.05404563      B
4      1  1.64959026 -0.10762260      B
5     NA  1.13528236 -0.04670294      A
6     NA  1.55636761  0.87617575      A
7     NA  0.40651924  1.90516887      A
8     NA  1.49827147  0.05080935      A
9     NA -0.04396752  0.53267040      A
10     1  0.42714137 -0.55944595      B

HTH

G

> I receive data from two different sites.
> One site is identified by an interger number, the other site has no data in
> column Plant=NA.
> 
> My pb:
> 
> I'm trying to assign labels "A" or "B" to these 2 sites into a new column,
> but my if(){} else{} statement fails with the following statement:
> Error in if (is.na(mat$Plant == TRUE)) { :
>         argument is of length zero
> 
> if(is.na(mat$Plant==TRUE)){mat$Plant1="A"} else{mat$Plant1="B"};

That's not how you use is.na(), see ?is.na, as is.na(x) returns
TRUE/FLASE depending on wither x is NA or not

> I looked through the avail doc and R-help for some time but wasn't able to
> fix the pb.
> 
> Thx Hans
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 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