Contingency Tables for all columns in a dataframe

Viewed 156

I have a dataframe with binary data (all factors) with the following structure:

Data:

convert tv radio print
0       1  1     0
1       0  1     1
0       0  0     0
1       0  0     1 

Question:

I want to have the proportion of convert==1 in percentage by each column of the dataframe, so imagine there are 100 rows, with 40 cases where convert == '1', then the proportion shown as rows (#tv==1/#convert==1)=0.98 and (#tv==0/#convert==1)=0.02

Expected Outcome:

value tv   radio print
0     0.02 0.42  0.70
1     0.98 0.58  0.30

Approach so far:

I am using prop.table inside a for loop, but it is not as elegant as I think is possible

2 Answers

One approach: Apply table() across the columns, then divide by the number of entries.

# making some junk data

df <- data.frame(
  convert = rbinom(100, 1, 0.4), 
  tv = rbinom(100, 1, 0.3),
  radio = rbinom(100, 1, 0.2),
  print = rbinom(100, 1, 0.4)
)

apply(df[df$convert == 1, -1], 2, table) / sum(df$convert == 1)

The column condition of -1 is to remove the first column (the trivial convert column) from the table.

We can also use tidyverse

library(dplyr)
library(purrr)
df %>% 
   filter(convert == 1) %>%  
   select(-1) %>% 
   map_dfc(~ table(.)/length(.))
Related