Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>One of the most important things when learning to program in R is to think in terms of vector operations rather than loops. You're getting <code>NA</code>s (not the same as <code>NaN</code> in R) in your two vectors because you're not filling all the locations: you're only filling locations in <code>densf</code> where you have <code>"raw"</code>, and locations in <code>densft</code> where you have <code>"cooked"</code>. What do you want R to fill the rest of the spaces with? <code>NA</code> is the default, but you can fill them with something else (zeros, for example) if you want. That's what I've done below.</p> <pre><code># your code N=1000 alpha=0.1 zerosandones = rbinom(N, 1,alpha) vector1=sample(c("raw","cooked"),1000,T,prob=c(0.12,.88)) # my code densf &lt;- ifelse(zerosandones == 1 &amp; vector1 == "raw", 1, 0) densft &lt;- ifelse(zerosandones == 0 &amp; vector1 == "raw", rbinom(N, 1,alpha*0.2), 0) </code></pre> <p>Things to note:</p> <ul> <li>The use of <code>ifelse</code>, which is a vectorized form of <code>if</code>.</li> <li>The use of <code>&amp;</code>, which is a vectorized form of <code>&amp;&amp;</code>.</li> <li>No loops! Loops in R are slow. Thinking in terms of vectors takes some adjustment, but is almost always better.</li> </ul> <p>When I ran this I got 12 ones in <code>densf</code> and 3 ones in <code>densft</code>, which is about what I would expect. If this is not what <em>you</em> expect, then you need to better explain what you're trying to do here and why you expect something different.</p>
    singulars
    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. 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