I'm currently making tables in R and am wondering if there is a way to make my process a lot less tedious. I"m making tables with two variables, however I am going through the levels of the first variable and creating a table for each level based off the second variable. An example of the code is below:
prop.table(table(df[df$v1 == 6 , c("v1" , "v2")]))*100
Variable v1 has 6 levels, i would like to create a loop that would start from 1 up to 6 (all variables are numeric, however not all of them end at 6) and generate tables for each level of v1 to v2.
Variable v2 has two levels, not sure if that is relevant but just in case it is.
Thank you!
EDIT: I've included sample code and desired output tables, apologies for not including these before!
EDIT2: Updated the tables to correctly show the expected outputs. My apologies for all the mistakes while posting this question, next questions will be much better formatted. Thank you everyone for your help!
id <- 1:20
age <- c(1, 2, 2, 3, 1, 1, 4, 5, 6, 6, 5, 4, 4, 4, 2, 1, 1, 2, 3, 1)
gender <- c(1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 3, 3, 2, 2, 2, 1, 2)
response <- c(1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1)
df <- data.frame(id, age, gender, response)
Here is an example of the table outputs I would like to see from the loop generated. It iterates through each level of the age variable (6 levels) with the response variable. I'd like this loop to apply to the gender variable as well, which has 5 levels.
| age | response (0) | response (1) |
|---|---|---|
| 1 | 67% | 33% |
| age | response (0) | response (1) |
|---|---|---|
| 2 | 50% | 50% |
| age | response (0) | response (1) |
|---|---|---|
| 3 | 100% | 0% |
| age | response (0) | response (1) |
|---|---|---|
| 4 | 50% | 50% |
| age | response (0) | response (1) |
|---|---|---|
| 5 | 50% | 50% |
| age | response (0) | response (1) |
|---|---|---|
| 6 | 50% | 50% |
Result