[R] Am I misunderstanding the ifelse construction?

Peter Dalgaard P.Dalgaard at biostat.ku.dk
Tue Sep 25 10:20:48 CEST 2007


Karin Lagesen wrote:
> I have a function like this:
>
> changedir <- function(dataframe) {
> dir <- dataframe$dir
> gc_content <- dataframe$gc_content
> d <- ifelse(dir == "-",
>             gc_content <- -gc_content,gc_content <- gc_content)
> return(d)
> }
>
> The goal of this function is to be able to input a data frame like this:
>
>
>   
>> lala
>>     
>    dir gc_content
> 1    +        0.5
> 2    -        0.5
> 3    +        0.5
> 4    -        0.5
> 5    +        0.5
> 6    -        0.5
> 7    +        0.5
> 8    -        0.5
> 9    +        0.5
> 10   -        0.5
> 11   +        0.5
> 12   -        0.5
> 13   +        0.5
> 14   -        0.5
> 15   +        0.5
> 16   -        0.5
> 17   +        0.5
> 18   -        0.5
> 19   +        0.5
> 20   -        0.5
>   
>
> And change the sign of the value of the gc_content field if the
> corresponding dir field is negative.
>
> Howver, when I run this through the changedir function, all of the
> gc_contents become negative.
>
> An I misunderstanding how to use the ifelse construct? And in that
> case, how should I go about doing this in a different way?
>
> Thankyou very much in advance for your help, and I hope that my
> question is not too banal!
>
> Karin
>   
Yes, you are misunderstanding it and you should study the examples on
the help page.

One key point is that (in general) both the 'yes' and 'no' get
evaluated, so having assignments to the same variable in there is a
really bad idea. Another point is that ifelse takes three _vectors_ and
returns a fourth.

I'd do

  result <- ifelse(dir=="-", -gc_content, gc_content)

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list