[R] if(){} else{}

Greg Snow Greg.Snow at intermountainmail.org
Tue Dec 5 17:25:53 CET 2006


Try this version:

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 <- transform(mat, Plant1=ifelse(is.na(Plant), "A","B"))


A couple of comments on your original code:

The 1:10 in the rnorm calls is unnecessary since rnorm just takes the
length of the vector, just tell rnorm how many numbers you want (or you
could do rnorm(Plant) to have R count for you).

The cbind function creates a matrix, the notation mat$Plant assumes that
mat is a list or data frame and that is why you received the error.

The  if (){} else {} syntax is usually for program flow and looks for a
scalar value, the function ifelse is vectorized and usefull for vectors
(which is what it looks like you wanted).

The transform function is nice in that it allows you to skip some of the
indexing.

Hope this helps,

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at intermountainmail.org
(801) 408-8111
 

-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Hans-Juergen
Eickelmann
Sent: Tuesday, December 05, 2006 8:33 AM
To: r-help at stat.math.ethz.ch
Subject: [R] if(){} else{}


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);
Value2<-rnorm(1:10);
mat<-cbind(Plant,Value1,Value2);
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"};

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.




More information about the R-help mailing list