I have this dataframe (let's imagine it has tens of variables)
set.seed(505)
df = data.frame(age_group = c(1,2,1,1,1,1,1,2,2,2,2,3,3,2,1,2,3),
score = trunc(runif(17,0,5)),
sex = trunc(runif(17,0,2)),
FO1 = trunc(runif(17,0,2)),
FN2 = trunc(runif(17,0,2)),
AL3 = trunc(runif(17,0,2)),
PM4 = trunc(runif(17,0,2)))
I want to create many frequency tables with their percentages. The tables include combinations of each FO1 , FN2 , AL3 , PM4 and each of age_group and score variables (without the sex variable). for example : table(df$FO1 ,df$age_group)
or table(df$FO1 ,df$score)
CodePudding user response:
one simple solution could be looping like this and using 'prop.table()':
cols1 <- c("FO1", "FN2", "AL3", "PM4")
cols2 <- c("age_group", "score")
for (i in cols1) {
for (j in cols2) {
cat(paste0("i = ", i, ", j = ", j, ":\n"))
print(prop.table(table(df[, i], df[, j])))
cat("\n")
}
}
Hope that helps!
Samuel