[R] loops and if statements

Laura Ferrero-Miliani laurafe at gmail.com
Sun Apr 18 14:46:38 CEST 2010


Hello,
I am very new to R and data analysis in general.
I am trying to generate values to append to my data frame using
conditional statements.
I am playing with this simple example:

a <- c(1:4)
b <- c("meep", "foo", "meep", "foo")
d <- cbind(a, b)

now what I want to do is , each time there is a "meep" in column 2 of
d, print "oops", else print "yay".
So I wrote:

for(i in seq(along=d[,2])) {if (d[i]=="meep") { print("oops")}
                                    else { print("yay")}
}

Result:
[1] "yay"
[1] "yay"
[1] "yay"
[1] "yay"

What am I doing wrong?

Furthermore, I would like to append the results to d:

d$c <- for(i in seq(along=d[,2])) {if (d[i]=="meep") { print("oops")}
                                    else { print("yay")}
}


this doesn't really work, it just turns the whole thing into a list.
.
Although if:

c <- NA
d <- cbind(a, b, c)

and I coerce d into a data.frame, run:

d$c <- for(i in seq(along=d[,2])) {if (d[i]=="meep") { print("oops")}
                                    else { print("yay")}
}


some glint of hope appears:


[1] "yay"
[1] "oops"

but then......



Error in if (d[i] == "meep") { : missing value where TRUE/FALSE needed
In addition: Warning messages:
1: In if (d[i] == "meep") { :
  the condition has length > 1 and only the first element will be used
2: In if (d[i] == "meep") { :
  the condition has length > 1 and only the first element will be used
3: In if (d[i] == "meep") { :
  the condition has length > 1 and only the first element will be used


To complicate things a little bit more in my real data there are 16
levels, so for each level I need to "print" a different value (that
would be 16 nested ifs, and I am sure there must be a more sensible
way to do this!)


Thanks in advance,

Laura



More information about the R-help mailing list