How to make a loop to create several contingency tables using columns from my dataframe?
This is part of my data frame:
structure(list(`Nombre del encuestado` = structure(c(1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L), .Dim = 20L, class = "table"), Municipio = c("IPIALES",
"IPIALES", "IPIALES", "IPIALES", "IPIALES", "IPIALES", "IPIALES",
"IPIALES", "IPIALES", "IPIALES", "IPIALES", "IPIALES", "IPIALES",
"IPIALES", "IPIALES", "IPIALES", "IPIALES", "IPIALES", "IPIALES",
"ARBOLEDA"), `Cuenta con sistema de Riego:` = c("NO", "NO", "NO",
"SI", "SI", "NO", "NO", "NO", "SI", "NO", "SI", "NO", "NO", "SI",
"SI", "NO", "NO", "SI", "NO", "NO"), `Procedencia del agua:` = c("Lluvia",
"Lluvia", "Lluvia", "Acueducto", "Acueducto", "Lluvia", "Lluvia",
"Lluvia", "Acueducto", "Lluvia", "Acueducto", "Lluvia", "Lluvia",
"Acueducto", "Acueducto", "Lluvia", "Lluvia", "Acueducto", "Lluvia",
"Lluvia"), `Cuenta con certificación en:` = c("Ningúna", "Ningúna",
"Ningúna", "Ningúna", "Ningúna", "Ningúna", "Ningúna", "Ningúna",
"Ningúna", "Ningúna", "Ningúna", "Ningúna", "Ningúna", "Ningúna",
"Ningúna", "Ningúna", "Ningúna", "Ningúna", "BPA", "Ningúna")), row.names = c(NA,
20L), class = "data.frame")
I need to use table function for each column with df$Municipio variable, somethink like this:
table(df$Municipio,
df$`Cuenta con sistema de Riego:`)
Results:
NO SI
ARBOLEDA 19 5
El Peñol 11 9
IPIALES 12 7
La Florida 14 6
Providencia 19 1
Sandona 17 2
Again:
table(df$Municipio,
df$`Procedencia del agua:`)
Results:
Acueducto Lluvia Rio/Qubrada/Nacimiento
ARBOLEDA 0 19 5
El Peñol 6 11 3
IPIALES 7 12 0
La Florida 0 14 6
Providencia 0 19 1
Sandona 2 17 0
Please, help me!
Many thanks
make a loop to create several contingency tables using columns from my dataframe
CodePudding user response:
As Municipio
is the second column, loop over all the columns with either index
ing (-2
) and get the table
of other column with the second column and store the output in a list
lapply(df[-2], function(x) table(x, df[[2]]))
Or use column names
lapply(setdiff(names(df), "Municipio"), function(nm) table(df[[nm]],
df$Municipio))