Reputation: 3158
I make a four way table with xtabs
library(magrittr)
xtabs( ~ vs + gear + cyl, data = mtcars) %>%
ftable(row.vars = "gear")
returns
vs 0 1
cyl 4 6 8 4 6 8
gear
3 0 0 12 1 2 0
4 0 2 0 8 2 0
5 1 1 2 1 0 0
Now I want proportions within levels of mtcars$vs
.
If I use prop.table
xtabs( ~ vs + gear + cyl, data = mtcars) %>%
ftable(row.vars = "gear") %>%
prop.table(margin = 1) %>%
round(2)
I get
vs 0 1
cyl 4 6 8 4 6 8
gear
3 0.00 0.00 0.80 0.07 0.13 0.00
4 0.00 0.17 0.00 0.67 0.17 0.00
5 0.20 0.20 0.40 0.20 0.00 0.00
Ie--I want the entry for vs == 0, gear == 3, cyl == 8, to be 1.00
Upvotes: 0
Views: 247
Reputation: 21
Try this
xtabs( ~ vs + gear + cyl, data = mtcars) %>%
ftable(row.vars = c("gear","vs")) %>%
prop.table(margin = 1) %>%
round(2)
the results are
cyl 4 6 8
gear vs
3 0 0.00 0.00 1.00
1 0.33 0.67 0.00
4 0 0.00 1.00 0.00
1 0.80 0.20 0.00
5 0 0.25 0.25 0.50
1 1.00 0.00 0.00
Upvotes: 2