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
with levels
in a custom order
library(dplyr)
csectionrisks1 <- csectionrisks %>%
mutate(across(c(infbin, nplan, risk, antib), factor, levels = c(1, 0)))
ftable(xtabs(n~antib+risk+nplan+infbin, data = csectionrisks1), row.vars=1:2)
-output
# nplan 1 0
# infbin 1 0 1 0
#antib risk
#1 1 11 87 1 17
# 0 0 0 0 2
#0 1 23 3 28 30
# 0 0 9 8 32
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 to factor
with levels
specified in the custom order