Calculations are R-based outputs either on or off a Page in the Report. This article describes how to add a custom R code Calculation to your Report. This can be used to create virtually anything, and is typically used to create a table, chart, text string, or an error message. A Calculation can also be referred to by other Calculations and Variables constructed using R code. If creating a basic R table, you can also use some Table Rules and the Appearance menu to apply formatting, see here for more info, or for more dynamic formatting, you can use the CreateCustomTable() function. Many times it is useful to develop custom code via a Calculation before creating a custom variable from R code in your Data Set so you can troubleshoot your code along the way.
Requirements
A Displayr document.
Method
1. In the toolbar or the right click + menu of the Report pane, click Calculation > Custom Code to insert an R-based output.
2. If putting on a Page using the toolbar menu, click on the page where you wish to place the calculation.
3. Enter your R code in the Code Editor above the page.
4. Click Calculate in the object inspector.
5. The object created by the final line of the code is returned. The Calculation is automatically named the name of the final object, or you can manually enter a name under General > General > Name.
5. OPTIONAL: You can adjust the display options under the Data > Show Advanced Options > Output:
- Show as lets you choose between text and table (when appropriate).
- Include R code lets you display the R code in a box next to the the result. The code will also be highlighted appropriately.
- Show raw R output shows the R terminal view where you see each line of code that is processed and anything that is printed. This is useful for troubleshooting R code as you can see which line of code is returning an error and preview intermediate objects and calculations in the script.
6. OPTIONAL: Under Appearance, you can adjust the decimal places and number format.
7. OPTIONAL: If you don't want your Calculation to automatically re-calculate when the data updates, uncheck Calculate automatically.
8. OPTIONAL: If you don't want to have this Calculation visible when your document is published, check General > Hidden from exports & publishing.
9. OPTIONAL: When outputting respondent-level data that matches the number of records in your data set, you can additionally apply a filter via Data > Filters & Weight > Filter(s).
Note, this will only work if you use QFilter
in your R code to filter your rows. Otherwise, you will get the following warning:
If you wish to apply filters to aggregated tables referenced in your code, or even a Standard R output such as a visualization, you will instead need to apply them to your source tables so your data can be filtered before aggregation.
Next
How to use the Filter(s) Dropdown to Quickly Filter R Outputs Using QFilter
How to Filter Raw Data Using R