Nonprofit-Open-Data-Collective / compensation-appraisal

A tool for automating compensation appraisal studies for nonprofit executives.
2 stars 1 forks source link

Outputting kables in a for loop #4

Closed olbeck closed 1 year ago

olbeck commented 1 year ago

Currently, in the file "graphs.html" that is generated by running unit-testing/run-comparisons-v03.R, each table that is outputted is just a raw output of a data.frame. I would like to output a kable (from knitr library).

The data frames that are not inside of a for loop output in a kable just fine.

Data frames that are inside a for loop will only output as a raw data table. I can not figure out how to print kables inside a for loop. I'd like to do something similar to what is mentioned here but this thread was never fully resolved.

lecy commented 1 year ago

It looks like print( kable(...) ) is generating raw text output, which is then returned as R output.

image

Have you tried adding results="asis" as a code chunk argument? That should embed the output directly in the RMD doc instead of printing it as code output. I'm not sure if it will work with print() though.

If not, there are lots of alternative functions for converting R tables to markdown tables. pander() tends to work well.

lecy commented 1 year ago

Or you can use cat() instead of print():


for( i in academic.units )
{

  cat( paste('<h1>', i ,'</h1>' ) )

  d %>%  
    filter( Department.Description == i ) %>% 
    create_salary_table() %>% 
    build_graph( unit=i )  

  cat( paste('<h3>', 'PAY RANGE BY RANK AND GENDER' ,'</h3>' ) )

  t.salary <- 
    d %>% 
    filter( Department.Description == i ) %>% 
    create_salary_table()

  cat( t.salary %>% knitr::kable(format="html") )

  # etc...

  cat( '<br><hr><br>' )

}

https://watts-college.github.io/cpp-527-fall-2021/labs/final-project-instructions.html

olbeck commented 1 year ago

The issue was with the kableExtra package. Using

for(i in 1:nrow(weights)){
  w <- unlist(weights[i, ])
  weight.table <- data.frame(level = 1:5,
             geo = c(w[2:4], NA, NA),
             r.mission = c(w[5:8], NA),
             s.mission = w[9:13] )
  rownames(weight.table) <- c()

  cat("Weight Set", i)
  print(kable(weight.table))
  cat("\n")
}

works just fine. Adding kable_styling to it also technically works, but then it interferes with the gridExtra and egg packages when arranging ggplots. So I've just deleted kable_styling and our tables won't be quite a pretty (although still readable) .