Note that there are some explanatory texts on larger screens.

plurals
  1. POProperly building a function in R
    primarykey
    data
    text
    <p>I'm writing my first function ever (including any other programming language) and I'm a little confused on the proper structure for <code>if</code>, <code>else</code> and <code>ifelse</code>. I've searched a ton of examples, but none are that clear to me. </p> <p>Situation - I'm trying to bucket clients by how long they have been clients for, then turn that into a factor. </p> <pre><code>#Sample Data clientID &lt;- round(runif(2,min=2000, max=3000),0) MonthsSinceSignUp &lt;- round(runif(20,min=1, max=60),0) df &lt;- data.frame(cbind(clientID,MonthsSinceSignUp)) </code></pre> <p>For a given client, I would like to determine if they have been so for less than a year, more than year, but less than 2, etc. </p> <p>This is my first crack at a function:</p> <pre><code>ClientAgeRange &lt;- function(MonthsSinceSignUp) { if (MonthsSinceSignUp &lt; 13) {ClientAgeRange &lt;- '1 year'} } else { if (MonthsSinceSignUp &gt; 13 &amp; MonthsSinceSignUps &lt; 25) {ClientAgeRange &lt;- '2 years'} } else {ClientAgeRage &lt;- '3+ years'} </code></pre> <p>The error that I keep getting is: <code>Error: unexpected '}' in "}"</code>, which would indicate I'm missing or have an extra closing bracket. However, despite my trouble shooting, I can't locate it. But - I think in general, I'm not apply the correct structure to the function. I'm trying to produce a <code>if this, then set this variable as that</code>. How can I structure this function properly?</p> <p>Lastly - if I wanted to add the output of the function to the <code>dataframe</code>, is <code>apply</code> the correct way to do so?</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.
 

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