Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to organize big R functions?
    primarykey
    data
    text
    <p>I'm writing an R function, that is becoming quite big. It admit multiple choice, and I'm organizing it like so:</p> <pre><code>myfun &lt;- function(y, type=c("aa", "bb", "cc", "dd" ... "zz")){ if (type == "aa") { do something - a lot of code here - .... } if (type == "bb") { do something - a lot of code here - .... } .... } </code></pre> <p>I have two questions:</p> <ol> <li>Is there a better way, in order to not use the 'if' statement, for every choice of the parameter type?</li> <li>Could it be more functional to write a sub-function for every "type" choice?</li> </ol> <p>If I write subfunction, it would look like this:</p> <pre><code>myfun &lt;- function(y, type=c("aa", "bb", "cc", "dd" ... "zz")){ if (type == "aa") result &lt;- sub_fun_aa(y) if (type == "bb") result &lt;- sub_fun_bb(y) if (type == "cc") result &lt;- sub_fun_cc(y) if (type == "dd") result &lt;- sub_fun_dd(y) .... } </code></pre> <p>Subfunction are of course defined elsewhere (in the top of myfun, or in another way).</p> <p>I hope I was clear with my question. Thanks in Advance.</p> <p><strong>- Additional info -</strong></p> <p>I'm writing a function that applies some different filters to an image (different filter = different "type" parameter). Some filters share some code (for example, "aa" and "bb" are two gaussian filters, which differs only for one line code), while others are completely different.</p> <p>So I'm forced to use a lot of if statement, i.e.</p> <pre><code> if(type == "aa" | type == "bb"){ - do something common to aa and bb - if(type == "aa"){ - do something aa-related - } if(type == "bb"){ - do something bb-related - } } if(type == "cc" | type == "dd"){ - do something common to cc and dd - if(type == "cc"){ - do something cc-related - } if(type == "dd"){ - do something dd-related - } } if(type == "zz"){ - do something zz-related - } </code></pre> <p>And so on. Furthermore, there are some if statement in the code "do something". I'm looking for the best way to organize my code. </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.
 

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