This article describes how to remove rows or columns from a table using R code in an R Output. The post contains the steps to go from the below table containing all brands and a NET column...
...to a table showing only Coke brands in rows and removing the NET column:
Requirements
- A table consisting of at least two rows and columns
- An R Output
For the purpose of all of the below examples, the name of the table we're referring to is "table". To find the name of your table you can right-click on it in the Report tree and select Reference name.
Method 1 - Specifying the rows/columns to remove by index
- Select your R output.
- Go to the object inspector > Properties > R CODE.
- Add the following code below any existing code.
To keep only the first three rows:
table[1:3,]
Alternatively, you can use a minus sign and specify the rows you don't wish to keep:
table[-(4:6),]
The above two examples will both return a table showing the first three rows of the data only.
However, if a table would change and contain row seven or eight, the second approach using a minus sign would return the first three rows as well as rows seven and eight.
To exclude a specific number of rows from the bottom of the table:
n = NROW(table)
table[-((n-1):n),]
The above code first counts the number of rows, storing the number as an n. The second line of code is saying to not return (minus sign) the second last to the last row (i.e., remove the last 2 rows).
Method 2 - Specifying the rows/columns to remove by name
- Select your R output.
- Go to the object inspector > Properties > R CODE.
- Add the following code below any existing code.
To remove the NET Column:
x = rownames(table)
y = colnames(table) != "NET"
table[x,y]
The above code stores the row names in x and column names excluding 'NET' in y. The last line brings both values together returning the below table:
The above code could be combined into one single line of code by replacing x and y in the last line with the code used to define these values in lines one and two, as per the next example.
To remove Pepsi from rows and the NET Column:
table[rownames(table) !="Pepsi",colnames(table) !="NET"]
Resulting table:
Method 3 - Specifying the rows/columns to remove by index and name
- Select your R output.
- Go to the object inspector > Properties > R CODE.
- Add the following code below any existing code.
To show only the first three brands/rows and remove the NET Column:
x = 1:3
y = colnames(table) !="NET"
table[x,y]
or just:
table[1:3, colnames(table) != "NET"]
Resulting table:
Next
How to Reference Different Items in Your Project in R
How to Relabel Rows and Columns in an R Table