mercredi 19 septembre 2018

Creating a list of contingency tables from variables in a data frame using for loop and if statement?

Sample of data frame:

 WasAdmitted concldur ArrivalDayWdWe IMDQuintile log_depdur
           1      130        Weekend          Q1   5.480639
           1      177        Weekday          Q1   5.370638
           0      125        Weekday          Q2   4.828314
           1      102        Weekday          Q5   5.220356
           1      203        Weekday          Q4   5.402677
           0      168        Weekday          Q2   5.123964

sample <- structure(list(WasAdmitted = c(1L, 1L, 0L, 1L, 1L, 0L), concldur = c(130L, 
177L, 125L, 102L, 203L, 168L), ArrivalDayWdWe = structure(c(2L, 
1L, 1L, 1L, 1L, 1L), .Label = c("Weekday", "Weekend"), class = "factor"), 
    IMDQuintile = structure(c(1L, 1L, 2L, 5L, 4L, 2L), .Label = c("Q1", 
    "Q2", "Q3", "Q4", "Q5"), class = "factor"), log_depdur = c(5.48063892334199, 
    5.37063802812766, 4.8283137373023, 5.22035582507832, 5.40267738187228, 
    5.12396397940326)), row.names = c(15109820L, 17598392L, 18282686L, 
10798602L, 9249317L, 17942470L), class = "data.frame")

I have WasAdmitted as my binary dependent variable of interest. I would like to produce a list of contingency tables of WasAdmitted against all other variables in my data frame, which are either type factor, integer or character, in to a list of the resultant contingency tables. So I'm excluding numeric variables.

As a start, I've created this:

for (i in sample){
if (typeof(i) %in% c("integer", "factor", "chr"))
  return(table(sample$i, sample$WasAdmitted))
}

However I'm not sure how to proceed from here.

Aucun commentaire:

Enregistrer un commentaire