Search code examples
rcontingency

Deriving contingency table from a bigger contingency table in R


I have a csv format contingency table made by python language , like this:

            case  control
disease_A    20    30 
disease_B    35    45
disease_C    42    52
disease_D    52    62

now i want to derive 2x2 contingency tables from this contingency table to calculate chi-square value using R

how can i derive a 2x2 table like the following from the contingency table above:

            case  control
disease_A    20    30 
disease_D    52    62

Thats probably a novice question but im new to R and i couldn't find the solution anywhere else


Solution

  • Here's an approach.

    The data:

    txt <-  "           case  control
    disease_A    20    30 
    disease_B    35    45
    disease_C    42    52
    disease_D    52    62"
    

    Read the data:

    dat <- read.table(textConnection(txt))
    #           case control
    # disease_A   20      30
    # disease_B   35      45
    # disease_C   42      52
    # disease_D   52      62
    

    Extract a subset of rows:

    dat2 <- dat[rownames(dat) %in% c("disease_A", "disease_D"), ]
    #           case control 
    # disease_A   20      30
    # disease_D   52      62