[R] Conditional statement

jim holtman jholtman at gmail.com
Mon Nov 16 14:08:35 CET 2009


Generate the numbers, test for zero and then set negatives to zero:

> set.seed(1)
> x <- rnorm(100,5,3)
> sum(x<0)
[1] 3
> x[x<0] <- 0
> sum(x<0)
[1] 0
>


On Mon, Nov 16, 2009 at 7:43 AM, Rafael Moral
<rafa_moral2004 at yahoo.com.br> 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.
>
> 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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?




More information about the R-help mailing list