[R] function on factors - how best to proceed

Gustaf Rydevik gustaf.rydevik at gmail.com
Wed Sep 19 15:04:05 CEST 2007


On 9/19/07, Karin Lagesen <karin.lagesen at medisin.uio.no> wrote:
> "Gustaf Rydevik" <gustaf.rydevik at gmail.com> writes:
>
>
> > The second warning message tells you that:
> >  2: the condition has length > 1 and only the first element will be
> > used in: if (terminus > origin)
> >
> > You are comparing two vectors,  which generate a vector of TRUE/FALSE values.
> > The "if" statement need a single TRUE/FALSE value.
> > Either use a for loop:
> > for (i in 1:nrow(terminus)) {if terminus[i]> origin[i]...}
> > or a nested ifelse statement (which is recommendable on such a big data set).
>
> Thankyou for your reply! I will certainly try the numeric thing.
>
> Now, for the vector comparison. I can easily see how you would do a
> for loop here, but I am unable to see how a nested ifelse statement
> would work. Could you possibly give me an example?
>
> Thankyou again for your help!
>
> Karin
> --
> Karin Lagesen, PhD student
> karin.lagesen at medisin.uio.no
> http://folk.uio.no/karinlag
>

You replace each instance of "if" with ifelse, inserting a comma after
the logical test, and instead of the else statement.  The end result
would become (if I've not made a mistake):

_____
replicator<-rep(c("LEFT","RIGHT"),50)
terminus<-rnorm(100)
origin<-rnorm(100)
begin<-rnorm(100)
length<-sample(1:100,100,replace=T)

d<-ifelse(terminus>origin,
	+ifelse(replicator=="LEFT",-((origin-begin))%%length),(begin-origin)),
	+ifelse(replicator=="LEFT",(origin-begin),-((begin-origin)%%length))
	+)

/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