Home > Enterprise >  expand a 2 by 2 contingency table
expand a 2 by 2 contingency table

Time:07-01

I have loaded data in the following format:

Gender Yes No
Male 2 1
Female 1 2

I would like to expand it to:

Gender Result
Male Yes
Male Yes
Male No
Female Yes
Female No
Female No

I've tried using the expand.table function in epitools but have not succeeded.

CodePudding user response:

Using tidyr, you can pivot the data into long format, then uncount it.

Assuming your data is called df, you could do that as follows:

library(tidyr)

pivot_longer(df, -Gender, names_to = 'Result') %>% 
  uncount(value)
#> # A tibble: 6 x 2
#>   Gender Result
#>   <chr>  <chr> 
#> 1 Male   Yes   
#> 2 Male   Yes   
#> 3 Male   No    
#> 4 Female Yes   
#> 5 Female No    
#> 6 Female No 

Data used, taken from question and put into reproducible format

df <- structure(list(Gender = c("Male", "Female"), Yes = 2:1, No = 1:2), 
                class = "data.frame", row.names = c(NA, -2L))

CodePudding user response:

Here is a data.table solution:

df1 <- data.frame(Gender = c("Male", "Female"), 
                  Yes = c(2,1), No = c(1,2))

library(data.table)

melt(setDT(df1), id.vars = "Gender")[,.SD[rep(.I, value)]][,value:=NULL][]

#>    Gender variable
#> 1:   Male      Yes
#> 2:   Male      Yes
#> 3: Female      Yes
#> 4:   Male       No
#> 5: Female       No
#> 6: Female       No

CodePudding user response:

Here is another solution based on data.table package:

library(data.table)

setDT(df)[, .(result = rep.int(c("Yes", "No"), c(Yes, No))), by=Gender]

#    Gender result
# 1:   Male    Yes
# 2:   Male    Yes
# 3:   Male     No
# 4: Female    Yes
# 5: Female     No
# 6: Female     No
  • Related