I want to reorder rows and columns of a ftable in R. Currently the table looks like this:
Now I want to switch the rows/columns, so that the counts for "1" are shown first, and for "0" second. For example the rows "antib" should switch, so that the row with counts for "1" is shown above counts for "0".
Is there a way to do this?
I used the following code and data:
library("tidyverse")
csectionrisks <- read.table("kaiserschnitt.raw",header=TRUE)
csectionrisks %>% mutate_if(is.character,as.numeric)
glimpse(csectionrisks)
attach(csectionrisks)
ftable(xtabs(n~antib+risk+nplan+infbin), row.vars=1:2)
The dataset I used can be downloaded here: Dataset
Thanks for your help!
One way is to convert to
factor
withlevels
in a custom order-output
The columns 'infbin', 'nplan', 'risk', 'antib' are
integer
class (after reading the data). The default ordering in integer is from lowest integer value to highest i.e. 0 to 1. To reverse that order, we convert tofactor
withlevels
specified in the custom order