[R] problems with ifelse??

David Winsemius dwinsemius at comcast.net
Mon Jul 11 03:27:01 CEST 2011


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)  )

-- 
David.
>
> Can someone tell me why this is happening??
>
> --
> View this message in context: http://r.789695.n4.nabble.com/problems-with-ifelse-tp3658498p3658498.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list