For my module #9 assignment I worked with tables and proportions in R. I practiced creating a contingency table, finding row and column totals and calculating proportions.
##create dataframe
assignment_data <- data.frame(
Country = c(“France”,”Spain”,”Germany”,”Spain”,”Germany”, “France”,”Spain”,”France”,”Germany”,”France”),
age = c(44,27,30,38,40,35,52,48,45,37),
salary = c(6000,5000,7000,4000,8000,5500,4500,6000,7500,5000),
Purchased = c(“No”,”Yes”,”No”,”No”,”Yes”,”Yes”,”No”,”Yes”,”No”,”Yes”)
)
##display the data frame
assignment_data
##output
##Country age salary Purchased
##1 France 44 6000 No
##2 Spain 27 5000 Yes
##3 Germany 30 7000 No
##4 Spain 38 4000 No
##5 Germany 40 8000 Yes
##6 France 35 5500 Yes
##7 Spain 52 4500 No
##8 France 48 6000 Yes
##9 Germany 45 7500 No
##10 France 37 5000 Yes
2. Generate contingency table also known as r x c table using mtcars dataset i.e. data(mtcars)
##load dataset
data(mtcars)
##create the contingency table labled assignment9
assignment9 <- table(mtcars$gear, mtcars$cyl, dnn = c(“gears”, “cylinders”))
##display the contingency table
assignment9
##output
## cylinders
##gears 4 6 8
## 3 1 2 12
## 4 8 4 0
## 5 2 1 2
2.1 Add the addmargins() function to report on the sum totals of the rows and columns of assignment9 table
>addmargins(assignment9)
addmargins(assignment9)
| ##output ##cylinders ##gears 4 6 8 Sum ## 3 1 2 12 15 ##4 8 4 0 12 ##5 2 1 2 5 ##Sum 11 7 14 32 |
2.2 Add prop.tables() function, and report on the proportional weight of each value in a assignment9 table
prop.table(assignment9)
##output
##cylinders
##gears 4 6 8
## 3 0.03125 0.06250 0.37500
## 4 0.25000 0.12500 0.00000
## 5 0.06250 0.03125 0.06250
2.3 Add margin = 1 to the argument under prop.table() function, and report on the row proportions found in assignment9 table.
prop.table(assignment9, margin = 1)
##output
##cylinders
##gears 4 6 8
## 3 0.06666667 0.13333333 0.80000000
##4 0.66666667 0.33333333 0.00000000
## 5 0.40000000 0.20000000 0.40000000
Leave a Reply