Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Instead of doing this:</p> <pre><code>sites10&lt;-as.factor(sample(sites,N*1)) sites5&lt;-as.factor(sample(sites,N*0.5)) sites1&lt;-as.factor(sample(sites,N*0.1)) </code></pre> <p>and running distinct loops for each of the three variables, you can make a general loop and put it in a function, then use one of the <code>-apply</code> functions to call it with specific parameters. For example:</p> <pre><code>N&lt;-10 # number of sites sites&lt;-factor(seq(from=1,to=N)) steps&lt;-10 P.stay&lt;-0.9 simulate.n.sites &lt;- function(n) { n.sites &lt;- sample(sites, n) result&lt;-matrix(0,nrow=steps) time.step&lt;-seq(1,steps) time.step&lt;-data.frame(time.step) time.step$event&lt;-0 j&lt;-numeric(steps) j[1]&lt;-sample(1:N,1) time.step$event[1]&lt;-j[1] for(i in 1:(steps-1)){ if(j[i] %in% n.sites){ ...etc... return(result) } results &lt;- lapply(c(1, 5, 10), simulate.n.sites) </code></pre> <p>Now <code>results</code> will be a list, with three matrix elements.</p> <p>The key is to identify places where you repeat yourself, and then refactor those areas into functions. Not only is this more concise, but it's easy to extend in the future. Want to sample for 2 site? Put a 2 in the vector you pass to <code>lapply</code>.</p> <p>If you're unfamiliar with the <code>-apply</code> family of functions, definitely look into those.</p> <p>I also suspect that much of the rest of your code could be simplified, but I think you've gutted it too much for me to make sense of it. For example, you define an element of time.step$event based on a condition, but then you overwrite that element. Surely this isn't what the actual code does?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload