data <- data.frame(Smoker=c(72L,34L),Non_Smoker=c(44L,53L),row.names = c("Male","Female"))
dataM <- as.matrix(data)
print(dataM)
Smoker Non_Smoker Male 72 44 Female 34 53
### calculate sum of table entries Using base functions
margin.table(dataM) # total members (marginal distribution)
print(margin.table(dataM, 1)) # row-wise summary total male and total females
print(margin.table(dataM, 2)) # column-wise summary total Smokers and total Non-Smokers
Male Female 116 87 Smoker Non_Smoker 106 97
addmargins(dataM) #adding marginal distribution summaries
Smoker | Non_Smoker | Sum | |
---|---|---|---|
Male | 72 | 44 | 116 |
Female | 34 | 53 | 87 |
Sum | 106 | 97 | 203 |
ftable(dataM)
Smoker Non_Smoker Male 72 44 Female 34 53
ftable(addmargins(dataM))
Smoker Non_Smoker Sum Male 72 44 116 Female 34 53 87 Sum 106 97 203
prop.table(table(dataM)) # this is better for single variable rather than two-way tables
dataM 34 44 53 72 0.25 0.25 0.25 0.25
prop.table(dataM, 1)
Smoker | Non_Smoker | |
---|---|---|
Male | 0.6206897 | 0.3793103 |
Female | 0.3908046 | 0.6091954 |
prop.table(dataM, 2)
Smoker | Non_Smoker | |
---|---|---|
Male | 0.6792453 | 0.4536082 |
Female | 0.3207547 | 0.5463918 |
prop.table(dataM)
Smoker | Non_Smoker | |
---|---|---|
Male | 0.3546798 | 0.2167488 |
Female | 0.1674877 | 0.2610837 |
#install.packages("gmodels")
library(gmodels)
CrossTable(dataM) # total contingency table using CrossTable function from gmodels package
Cell Contents |-------------------------| | N | | Chi-square contribution | | N / Row Total | | N / Col Total | | N / Table Total | |-------------------------| Total Observations in Table: 203 | | Smoker | Non_Smoker | Row Total | -------------|------------|------------|------------| Male | 72 | 44 | 116 | | 2.156 | 2.356 | | | 0.621 | 0.379 | 0.571 | | 0.679 | 0.454 | | | 0.355 | 0.217 | | -------------|------------|------------|------------| Female | 34 | 53 | 87 | | 2.875 | 3.142 | | | 0.391 | 0.609 | 0.429 | | 0.321 | 0.546 | | | 0.167 | 0.261 | | -------------|------------|------------|------------| Column Total | 106 | 97 | 203 | | 0.522 | 0.478 | | -------------|------------|------------|------------|
%>%
from magrittr
package¶Data transformation
https://r4ds.had.co.nz/transform.html