[R] problem with ifelse

Sarah Goslee sarah.goslee at gmail.com
Wed May 30 20:32:13 CEST 2012


Hi,

The error with ifelse() seems to be that you have no idea what ifelse() does.

As far as I can tell, you tried to construct code that does something like this:


y<-function(tdata,v){
   z <- rep(NA, length(tdata))
   s <- z
   for(i in 1:length(tdata)) {
      for(j in 1:length(v-1)) {
			if(tdata[i] > v[j] & tdata[i] < v[j+1]) {
				z[i]<-v[j]
				s[i]<-v[j+1]
			}
		}
	}
   return(cbind(z,s))
}

But what's with all the (( instead of ))?

And are you certain that the logic in the if statement is correct?

If you tell us what you expect the results to be for given input
values, we can help with that part too. Including making this more
Rish: the nested for-loop construct is entirely unnecessary here, but
I'm disinclined to rewrite it unless I actually know what you're
trying to achieve.

Incidentally, your example is only nearly-reproducible, since we don't
know what m is.

Sarah

On Wed, May 30, 2012 at 10:01 AM, Christopher Kelvin
<chris_kelvin2001 at yahoo.com> wrote:
> Dear all,
>  The code below is used to generate interval censored data but unfortunately there is an error with the ifelse which i am not able to rectify.
>  Can somebody help correct it for me.
> Thank you
>
>
> t<-rexp(20,0.2)
> v<-c(0,m,999)
>
> y<-function(t,v){
>   z<-numeric(length(t ((
>     s<-numeric(length(t ((
>       for(i in 1:length(t)){
>         for(j in 1:length(v-1))
>         { ifelse ((t[i]>v[j] & t< v[j+1] ),{z[i]<-v[j];s[i]<-v[j+1]},NA)}}
>       return(cbind(z,s))}
>
> y(t,v)
>


-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list