Introduction
If your R Output uses variables or a raw data table as an input (as opposed to a table/visualization/other output), you can use the standard Filter: dropdowns to quickly filter your R Output. These are referenced using QFilter
in R code and will automatically update based on the filters applied to R Output without the need to edit the R code. This is useful when showing raw data as your final output or if you'd like to filter raw data used in a custom calculation.
For example, you can go from this showing all responses in the data set:
To this showing only those records filtered in using the Filter: dropdowns:
Or this showing a custom output only including the filtered responses, such as a table of counts of each response:
Requirements
- An R Output that uses variables from the data set or an unfiltered raw data table.
- One or more filter variables from the same data set.
Method
In this example, we will return a list of the ages for Females in our data set using the Filter: dropdown. Note there are 600 records in total in the dataset.
1. Paste the following in the R CODE box of your R Output, note our variable is named Age:
Age[QFilter]
2. Using the Filter: dropdowns, apply the desired filter variable(s). If you apply multiple filters, they are joined using AND logic, and all filters must be met to be filtered into the code. Here, we will apply a Female filter:
Our R output now returns 301 records, the same number as females in our data set.
3. Your final results doesn't need to be raw data, you can do further calculations with the filtered data to output a custom final result. Change the R CODE to the following to show a table of counts for each age sorted in decreasing order for Females (or whatever filters are applied):
sort(summary(Age[QFilter]),decreasing=T)
Notes
QFilter
automatically updates when the filters change.- This example uses a single variable, so we use
[QFilter]
after the variable name. If you're wanting to filter multiple variables joined together in a Question or manually using cbind() or data.frame(), you need to use the [rows, columns] syntax instead[QFilter,]
. - If no filters are applied, it takes a value of
TRUE
and filters in all responses. - If you apply filters to your R Output via Filter: but do not include
QFilter
in your code, you will receive the following warning: - The Filter Label is available as an attribute (i.e.,
attr(QFilter, "label")
). Where there are multiple filters, they are concatenated as a list (e.g., "Male, 18 to 24 and Tall"). - The Filter Name (though sometimes not human readable) is available as an attribute (i.e.,
attr(QFilter, "name")
). Where there are multiple names, they are concatenated as with labels.
See Also
How to Work with Conditional R Formulas
How to Filter Raw Data Using R
Comments
0 comments
Article is closed for comments.