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!
Asked
Active
Viewed 1,086 times
2 Answers
2
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")

Chriss Paul
- 1,101
- 6
- 19
-
'age+Breathless~ wheeze' sets 'age' and 'Breathless' to be on the row, 'wheeze' to be on the column? – siegfried Oct 14 '20 at 00:15
-
Yes, think about it like what you have before `~` stays as rows and what is after `~` is kind of transposed to columns, and the values you want to fill in the reshaped table will be in argument `value.var`. Check `?dcast` for more details – Chriss Paul Oct 14 '20 at 00:27
1
An option with tidyverse
would be
library(dplyr)
library(tidyr)
data %>%
pivot_wider(names_from = wheeze, values_from = count)

akrun
- 874,273
- 37
- 540
- 662
-
Thank you for your answer! Is the names_from argument for the factor I wish to set in the column of the table, in this case 'wheeze'? – siegfried Oct 14 '20 at 00:09