Refactoring R Code
Architect contains easy-to-use tools to quickly make alterations to your code. Below, we display how to use these functionalities.
Extracting Local Variables
Suppose we have some expressions that are reused throughout our code. In the example below, we have repeated instances of the expression:
profit > 0 & revenue > 50000
To clean up our code, we may be interested in assigning this expression to a variable, and replacing all instances of said expression by our new variable. We can do this by highlighting the specified code and selecting ‘Source > Extract Local Variable…’. The extraction is shown below.
Renaming Variables in a Selected Region
In the Tips and Tricks Section, we showed how to rename all instances of a variable in an entire document. However, often one wishes to rename a variable in just a specific section of the code.
We can do this by selecting a given section of code and selecting Source > Rename in Selected Region…. This opens a window the displays all variables within the selected region. Navigate to a variable and type another name in the New Name column to rename that variable in the highlighted region.
Converting Code into a Function
In Architect, a chunk of code can be transformed into a function with the click of a button. Simply highlight the desired code and select Source > Extract R Function…. Architect will automatically detect the function’s necessary input parameters, at which point you can specify their order in the function call. The code is wrapped into a function, and a function call is given underneath the definition.
In the example below, we wrap some code for a residual plot into a ‘plotResiduals’ function that takes ‘x’ and ‘y’ as inputs.