Reputation: 862
I am struggling to create list of tables (object = table, not data.frame) by loop in R. Structure of my data is also a little bit complicated - sometimes the table function do not give 2x2 table - how to fill tables with incomplete dimensions to 2x2 automatically?
Sample data (in real dataset much much larger...)
my.data <- data.frame(y.var = c(0,1,0,1,1,1,0,1,1,0),
sex = rep(c("male","female"), times = 5),
apple = c(0,1,1,0,0,0,1,0,0,0),
orange = c(1,0,1,1,0,1,1,1,0,0),
ananas = c(0,0,0,0,0,0,0,0,0,0))
# y.var sex apple orange ananas
# 1 0 male 0 1 0
# 2 1 female 1 0 0
# 3 0 male 1 1 1
Look into creating tables - for apple I have nice 2x2 tables
table(my.data$y.var, my.data$apple)
# 0 1
# 0 2 2
# 1 5 1 .... Ok, nice 2x2 table.
table(my.data$y.var, my.data$apple, my.data$sex)
# , , = female
# 0 1
# 0 1 0
# 1 3 1
# , , = male
# 0 1
# 0 1 2
# 1 2 0 .... Ok, nice 2x2 table.
However for ananas I have only 2x1 tables
table(my.data$y.var, my.data$ananas)
# 0 # 0 1
# 0 4 # 0 4 0
# 1 6 .... NOT Ok! I need 2x2 table like this: # 1 6 0
table(my.data$y.var, my.data$ananas, my.data$sex)
# , , = female
# 0 # 0 1
# 0 1 # 0 1 0
# 1 4 .... NOT Ok! I need 2x2 table like this: # 1 4 0
# , , = male
# 0 # 0 1
# 0 3 # 0 3 0
# 1 2 .... NOT Ok! I need 2x2 table like this: # 1 2 0
I can do list manually like this, however this is not very practical.
my.list <- list(table(my.data$y.var, my.data$apple),
table(my.data$y.var, my.data$apple, my.data$sex),
table(my.data$y.var, my.data$orange),
table(my.data$y.var, my.data$orange, my.data$sex),
table(my.data$y.var, my.data$ananas),
table(my.data$y.var, my.data$ananas, my.data$sex))
How to do self-correcting-table-dimensions-loop? Necessary for following analyses...
Upvotes: 2
Views: 1033
Reputation: 886978
We can use lapply
to loop over the list of columns after converting the columns of interest to have the same levels
with factor
and then do a table
and keep the output in the list
my.data[-2] <- lapply(my.data[-2], factor, levels = 0:1)
lst1 <- lapply(my.data[3:5], function(x) table(my.data$y.var, x))
Upvotes: 1