Skip to content
Prev 105574 / 398506 Next

if(){} else{}

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,