siegfried
siegfried

Reputation: 451

Construct 3-way contingency table in R

The 4 variables I have are: Breathless(B)= {y,n}, wheeze(W)= {y,n}, age={g1,g2,...,g5}, and count= {20 numeric counts}. I would like to construct a table as shown in the image, however the ftable function is unable to arrange the output properly into a table. How else can I construct it? Thanks in advance!

enter image description here enter image description here

The output from ftable function: enter image description here

Upvotes: 1

Views: 1432

Answers (2)

akrun
akrun

Reputation: 887078

An option with tidyverse would be

library(dplyr)
library(tidyr)
data %>%
     pivot_wider(names_from = wheeze, values_from = count)

Upvotes: 1

Chriss Paul
Chriss Paul

Reputation: 1101

You can try to reshape your data using dcast from data.table

library(data.table)
setDT(data)
dcast(data, age + Breathless ~ wheeze, value.var = "count")

Upvotes: 2

Related Questions