[R] loops and if statements

Erich Neuwirth erich.neuwirth at univie.ac.at
Sun Apr 18 18:04:55 CEST 2010


I would prefer version 1.
Version to creates a global variable R which you do not really need
since it contains the same values as d$r.
In option 2, you should probably remove the variable r itself
after it has been appended to d.


On 4/18/2010 5:23 PM, Laura Ferrero-Miliani wrote:
> Thanks for correcting my code Erich, do you think what I wrote is
> overcomplicating things? Considering what Juan wrote:
> 
> # Option 1
> a <- 1:4
> b <- c("meep", "foo", "meep", "foo")
> d <- data.frame(a, b)
> d$r <- with(d, ifelse(b == 'meep', 'oops', 'yay'))
> d
> 
> # Option 2
> a <- 1:4
> b <- c("meep", "foo", "meep", "foo")
> d <- cbind(a, b)
> r <- ifelse(d[,2] == 'meep', 'oops', 'yay')
> d <- cbind(d, r)
> d
> 
> 
> On Sun, Apr 18, 2010 at 5:13 PM, Erich Neuwirth
> <erich.neuwirth at univie.ac.at> wrote:
>>> for(i in seq(along=d[,2])) {if (d[i,2]=="meep") { print("oops")}
>>>                                     else { print("yay")}
>>> }
>> is probably what you want.
>> But the way you are using cbind converts a into a vector of
>> character. It is not numeric any more.
>> Perhaps you want
>>
>> d<-cbind(as.data.frame(a),b)
>>
>> And then you could do
>>
>> for (el in d$b) print(ifelse(el=="meep","oops","yay"))
>>
>> On 4/18/2010 2:46 PM, Laura Ferrero-Miliani wrote:
>>> for(i in seq(along=d[,2])) {if (d[i]=="meep") { print("oops")}
>>>                                     else { print("yay")}
>>> }
>>
>> --
>> Erich Neuwirth, University of Vienna
>> Faculty of Computer Science
>> Computer Supported Didactics Working Group
>> Visit our SunSITE at http://sunsite.univie.ac.at
>> Phone: +43-1-4277-39464 Fax: +43-1-4277-39459
>>
> 
> 

-- 
Erich Neuwirth, University of Vienna
Faculty of Computer Science
Computer Supported Didactics Working Group
Visit our SunSITE at http://sunsite.univie.ac.at
Phone: +43-1-4277-39464 Fax: +43-1-4277-39459



More information about the R-help mailing list