2

I'm using the epiR package as it does nice 2 by 2 contingency tables with odds ratios, and population attributable fractions.

As is common my data is coded 0 = No 1 = Yes

So when I do

tabele(var_1,var_2)

The output comes out as a table aligned like

enter image description here

For its input though epiR wants the top left square to be Exposed+VE Outcome+VE - i.e the top left square should be Var 1==1 and Var 2==1

Currently I do this by recoding the zeroes to 2 or alternatively by setting as a factor and using re-level. Both of these are slightly annoying for other analyses as in general I want Outcome+VE to come after Outcome-VE

So I wondered if there is an easy way (?within table) to flip the orientation of table so that it essentially inverts the ordering of the rows/columns?

Hope the above makes sense - happy to provide clarification if not.


Edit: Thanks for suggestions below; just for clarification I want to be able to do this when calling table from existing dataframe variable - i.e when what I am doing is table(data$var_1, data$var_2) - ideally without having to create a whole new object

zx8754
  • 52,746
  • 12
  • 114
  • 209
mmarks
  • 1,119
  • 7
  • 14

2 Answers2

7

Table is a simple matrix. You can just call indices in reverse order.

xy <- table(data.frame(value = rbinom(100, size = 1, prob = 0.5),
           variable = letters[1:2]))

     variable
value  a  b
    0 20 22
    1 30 28

xy[2:1, 2:1]

     variable
value  b  a
    1 20 30
    0 30 20
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
  • Thanks - is there a way to do this when calling table from existing dataframe - i.e when what I am doing is table(data$var_1, data$var_2) – mmarks Nov 26 '18 at 22:19
3

Using factor levels:

# reproducible example (adapted from Roman's answer)
df1 <- data.frame(value = rbinom(100, size = 1, prob = 0.5),
                  variable = letters[1:2])

table(df1)
#      variable
# value  a  b
#     0 32 23
#     1 18 27

#convert to factor, specify levels
df1$value <- factor(df1$value, levels = c("1", "0"))
df1$variable <- factor(df1$variable, levels = c("b", "a"))

table(df1)
#      variable
# value  b  a
#     1 24 26
#     0 26 24
zx8754
  • 52,746
  • 12
  • 114
  • 209
  • Thanks - as mentioned above I'm trying to find an example that doesn't involve actually altering the values - because its a quirk of epiR that it wants this layout so I just want something to flip the values essentially within the call to function – mmarks Nov 26 '18 at 22:16
  • 1
    then `table(transform(df1, value = factor(value, levels = c("1", "0"), variable = factor(variable, levels = c("b", "a")))` – moodymudskipper Dec 02 '18 at 02:29