[R] Conditional statement

David Winsemius dwinsemius at comcast.net
Mon Nov 16 14:13:21 CET 2009


On Nov 16, 2009, at 7:43 AM, Rafael Moral wrote:

> Dear useRs,
>
> I wrote a function that simulates a stochastic model in discrete time.
> The problem is that the stochastic parameters should not be negative  
> and sometimes they happen to be.
> How can I conditionate it to when it draws a negative number, it  
> transforms into zero in that time step?
>
> Here is the function:
>
> stochastic_prost <- function(Fmean, Fsd, Smean, Ssd, f, s, n, time,  
> out=FALSE, plot=TRUE) {
> nt <- rep(0, time)
> nt[1] <- n
> for(n in 2:time) {
> nt[n] <- 0.5*rnorm(1, Fmean, Fsd)*rnorm(1, Smean, Ssd)*exp(1)^(-(f 
> +s)*nt[n-1])*nt[n-1]}
> if(out==TRUE) {print(data.frame(nt))}
> if(plot==TRUE) {plot(1:time, nt, type='l', main='Simulation',  
> ylab='Population', xlab='Generations')}
> }
>
> The 2 rnorm()'s should not be negative; when negative they should  
> turn into zero.

       ...*max(0, rnorm(1, Fmean, Fsd)*max(0, rnorm(1, Smean, Ssd)*...

> Thanks in advance,
> Rafael
>
>
>       
> ____________________________________________________________________________________
> [[elided Yahoo spam]]
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list