This article describes how to go from an unsorted R table...
...to a table that is sorted on a particular column (e.g., Male).
Requirements
One of the following:
- A crosstab with one question selected in rows and one selected in columns.
- A summary table with at least two rows and one column.
Method
- Select your table.
- From the object inspector
, go to General > General > Name and copy the table name.
- Select Calculation
> Custom Code from the toolbar.
- Click on the page to place the custom code object.
- Add a line to the R Code editor that defines the table as
table = table_nameusing the table_name as copied from step 2. - Add another line to that code
table[order(table[,column_name], decreasing = TRUE),]where column_name is the name of the column you wish to sort by in descending order. Instead of the column name, you can also use the column index (e.g., "1" for the first column, "2" for the second column, etc.) - OPTIONAL: to show the table in ascending order, replace decreasing = TRUE with decreasing = FALSE.
This example code takes a table called table.Preferred.cola.by.D3.Gender and sorts it in descending order by the Male column:
table = table.Preferred.cola.by.D3.Gender
table = table[order(table[,"Male"], decreasing = TRUE),]The example code below uses the same table and sorts it in ascending order by the first column containing data (Male column).
table = table.Preferred.cola.by.D3.Gender
table = table[order(table[,1], decreasing = FALSE),]
UPCOMING WEBINAR: The Roadmap for Market Researchers in the Age of AI