title: How to code a piecewise function in R for a little simulation and store values in a data frame
body: <p>I need to put in code a piecewise function and store generated values in a data frame. The rules are the following:</p>
  
  <ul>
  <li>I have an object X that is generated by a Bernoulli(1/3).</li>
  <li>If X=0, another object, Y, is generated by E = Exponential(1).</li>
  <li>If X=1, Y is generated by E if E &lt;= P, and by (P + EL) if E > P, where P is a constant (1, for example) and EL = Exponential(Lambda) independent from E.</li>
  <li>I want to generate a data frame with 100 samples of X and Y obtained using this method, and additionally, do this process 10000 times (or in other words, generate 10000 data frames).</li>
  </ul>
  
  <p>I tried to do something like this, but as I'm a total novice using R, I couldn't figure out how to define properly each element, and obviously, how to store my results in a data frame.</p>
  
  <p>Here's the "code" I did:</p>
  
  <pre><code>test &lt;- function(lambda,p) {
  for (i in 1:10000) { # Number of simulations that I want to do.
  for(j in 1:100) { # Sample size of each simulation / data frame.
    x &lt;- rbinom(1,1,1/3)
    e &lt;- rexp(1,1)
    if (x==0) {y &lt;- e}
    else {
      if (e&lt;=p) {y &lt;- e}
    else {y &lt;- p + rexp(1, lambda)}
      }
    }
  }    
  </code></pre>
  
  <p>But even before testing I know it's impossible that it works properly. The data frame that I want to make only may contain values for X and Y.</p>
  
  <p>I know this could be a very basic question, so thank you very much for your answers.</p>