Stack Overflow Asked on January 1, 2022
I’m trying to make sense of some data with a two-way table (using gmodels
– but I am open to doing this in a tidyverse way too) and I can’t work out how to control the order of the columns and the rows.
I would like TRUE
to be the first column, and TRUE
to be the first row. Here’s some code I have.
library(gmodels)
# some dummy data
df <- tibble(green = c(TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE),
pink = c(FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE))
CrossTable(
df$pink,
df$green,
prop.r = FALSE,
prop.t = FALSE,
prop.c = FALSE,
prop.chisq = FALSE,
chisq = FALSE
)
The above code produces output in a different column/row order than I want:
| df$green
df$pink | FALSE | TRUE | Row Total |
-------------|-----------|-----------|-----------|
FALSE | 2 | 2 | 4 |
-------------|-----------|-----------|-----------|
TRUE | 4 | 1 | 5 |
-------------|-----------|-----------|-----------|
Column Total | 6 | 3 | 9 |
-------------|-----------|-----------|-----------|
But what I want to see is something like this (which I’ve done by hand):
| df$green
df$pink | TRUE | FALSE | Row Total |
-------------|-----------|-----------|-----------|
TRUE | 1 | 4 | 5 |
-------------|-----------|-----------|-----------|
FALSE | 2 | 2 | 4 |
-------------|-----------|-----------|-----------|
Column Total | 3 | 6 | 9 |
-------------|-----------|-----------|-----------|
thanks!
You can try with base function table and convert it to data.frame and change the order of column
Here is the code
as.data.frame.matrix(table(df))[,c("TRUE","FALSE")]
Answered by Ganesh Shastry on January 1, 2022
You need to use ordered factors. try this
library(gmodels)
library(dplyr)
# some dummy data
df <- tibble(green = factor(c(TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE), levels = c('TRUE', 'FALSE')),
pink = factor(c(FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE), levels = c('TRUE', 'FALSE')))
CrossTable(
df$pink,
df$green,
prop.r = FALSE,
prop.t = FALSE,
prop.c = FALSE,
prop.chisq = FALSE,
chisq = FALSE
)
and you will get this:
| df$green
df$pink | TRUE | FALSE | Row Total |
-------------|-----------|-----------|-----------|
TRUE | 1 | 4 | 5 |
-------------|-----------|-----------|-----------|
FALSE | 2 | 2 | 4 |
-------------|-----------|-----------|-----------|
Column Total | 3 | 6 | 9 |
-------------|-----------|-----------|-----------|
Answered by Reza on January 1, 2022
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP