[R] problems with ifelse??

Berend Hasselman bhh at xs4all.nl
Mon Jul 11 10:02:01 CEST 2011


David Winsemius wrote:
> 
> On Jul 10, 2011, at 9:09 PM, mousy0815 wrote:
> 
>> I have the following code to determine the probability of a t-cell
>> encountering an antigen after "m" steps.
>>
>> probability <- function(N, f, m, b, x, t) { #using ifelse instead of  
>> if/else
>> 	#N is the number of lymph nodes
>> 	#f is the fraction of Dendritic cells (in the correct node) that  
>> have the
>> antigen
>> 	#m is the number of time steps
>> 	#b is the starting position (somewhere in the node or somewhere in  
>> the gap
>> between nodes. It is a number between 1 and (x+t))
>> 	#x is the number of time steps it takes to traverse the gap
>> 	#t is the number of time steps it takes to traverse a node.
>> 	A <- 1/N
>> 	B <- 1-A
>> 	C <- 1-f
>> 	D <- (((m+b-1)%%(x+t))+1)
>> 	
>> 	ifelse(b<=t, ########starts inside node
>> 			ifelse( (m<=(t-b)),
>> 					return(B + A*(C^m)), # start & end in first node
>> 					ifelse (D<=t,  # we finish in a node
>> 							return((B + A*(C^(t-b)))*((B + A*(C^t))^(floor(m/(x 
>> +t))-1))*(B +
>> A*(C^D))),
>> 							probability(N, f, (m-1), b, x, t)
>> 						)
>> 				),
>> 			ifelse( ########starts outside node
>> 				m<=(x+t-b),
>> 				return(1), #also end in the gap,
>> 				ifelse (
>> 					(D<=t), #end in a node
>> 					(return(((B + A*(C^t))^(floor((m/(x+t)))))*(B + (A*(C^D))))),
>> 					probability(N, f, (m-1), b, x, t)#outside node
>> 					)
>> 				)	
>> 			)	
>> 	}
>>
>> But I do:
>>> m<- c(1:3)
>>> probability(10, 0.1, m, 3, 4, 5)
>> 0.9900000 0.9810000 0.9729000
>>
>> but if you do each number separately you get
>>> probability(10, 0.1, 1, 3, 4, 5)
>> 0.99
>>> probability(10, 0.1, 2, 3, 4, 5)
>> 0.981
>>> probability(10, 0.1, 3, 3, 4, 5)
>> 0.981
> 
> Your function is probably not fully vectorized. Try comparing with
> 
> sapply(1:3, function(x) probability(  m =x, N=0.1, f=3,  b=3, x=4,  
> t=5)  )
> 

Shouldn't that be

sapply(1:3, function(x) probability(m =x, N=10, f=0.1, b=3, x=4, t=5))

@mousy

Your function uses ifelse which is a function that takes a vector as first
argument.
In the inner ifelse's you do a return().
So if any element of the condition vector implies that a return-branch must
be taken, your function
will immediately return a vector which is filled with values which may not
be correct for other entries in the condition vector.

Is m supposed to be a vector? If not then it may be a good idea to test for
that.
If not then why are you using ifelse? if {} else {} would be better.

Berend





 

--
View this message in context: http://r.789695.n4.nabble.com/problems-with-ifelse-tp3658498p3658902.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list