[R] Am I misunderstanding the ifelse construction?
Gustaf Rydevik
gustaf.rydevik at gmail.com
Tue Sep 25 10:27:10 CEST 2007
On 9/25/07, Karin Lagesen <karin.lagesen at medisin.uio.no> 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
> --
Hej igen!
The ifelse(x,a,b) returns a vector whose elements are picked from
either a or b depending on whether x is true or false. However it
evaluates both the a and the b vector. Since you are changing
gc_content in both a and b, strange things are bound to happen. The
easiest way would be to just skip the assignment in the ifelse
construct.
Like so:
changedir <- function(dataframe) {
dir <- dataframe$dir
gc_content <- dataframe$gc_content
d <- ifelse(dir == "-",
-gc_content,gc_content)
return(d)
}
Hope it helps!
best,
Gustaf
--
Gustaf Rydevik, M.Sci.
tel: +46(0)703 051 451
address:Essingetorget 40,112 66 Stockholm, SE
skype:gustaf_rydevik
More information about the R-help
mailing list