dcomtois / summarytools

R Package to Quickly and Neatly Summarize Data
523 stars 78 forks source link

Using a for loop to create cross-tables for several independent variables and the outcome variable #131

Closed MoutasemZ closed 3 years ago

MoutasemZ commented 3 years ago

I tried this piece of code

for (i in 1:length (VarVector)){ mycol = VarVector[i]

print (ctable(x = mydata$com_rep, y = mydata[[mycol]] , totals = FALSE, headings = FALSE, prop = "t") , method = "render" ) }

I don't get any output printed. If I tried a single statement outside the loop it works, for example:

mycol = VarVector[1] print (ctable(x = mydata$com_rep, y = mydata[[mycol]] , totals = FALSE, headings = FALSE, prop = "t") , method = "render" )

So why is that ?

dcomtois commented 3 years ago

Here's a Stack Overflow question that sheds some light on the topic: https://stackoverflow.com/questions/4716152/why-do-r-objects-not-print-in-a-function-or-a-for-loop

Oddly enough, there's an easy way around this... just encapsulate the print() in another print():

VarVector <- c("smoker", "diseased")
for (i in 1:length(VarVector)) {
  mycol = VarVector[i]

  print(
    print(ctable(x = tobacco$gender, y = tobacco[[mycol]] ,
                 totals = FALSE, headings = FALSE, prop = "t"),
          method = "render")
  )
}