Search code examples
rreshape2tidyrsplitstackshape

How do I convert a 2x2 contingency table into a long format dataframe?


How do I convert a 2x2 contingency table into a long format data frame? I tried this:

library(reshape2)
Table <- matrix(c(7,67,19,71), 2, 2, byrow=TRUE)
rownames(Table) <- c('Drug', 'No_Drug')
colnames(Table) <- c('Comp', 'No_Comp')
melt(Table)

I get this rather than a data frame of 164 rows categorized by Drug vs. No_Drug

  Var1    Var2 value
1    Drug    Comp     7
2 No_Drug    Comp    19
3    Drug No_Comp    67
4 No_Drug No_Comp    71

Solution

  • From what I understand, you are trying to convert your 4x3 molten data.frame into a 164x2 data.frame. You could try expandRows() from the splitstackshape package:

    Expands (replicates) the rows of a data.frame or a data.table, either by a fixed number, a specified vector, or a value contained in one of the columns in the source data.frame or a data.table.

    In your case, simply do:

    library(splitstackshape)
    m <- melt(Table)
    expandRows(m, "value") 
    

    Note: This is a convenient wrapper around base R:

    out <- m[rep(sequence(nrow(m)), m[["value"]]), ]
    out[["value"]] <- NULL