rfor-looprstudioknitrpander

Generating pander tables in a loop in RMarkdown in Rstudio


I've a set of tables that I'm generating with use of the code similar to the snippet below:

```{r tables, echo=TRUE, eval=TRUE}
require(reshape2); require(pander)
data("mtcars")
data("AirPassengers")

dta_lst <- list(mtcars, AirPassengers)
for (i in 1:length(dta_lst)) {
    pander(melt(head(dta_lst[[i]], n = 2), varnames = c("Something"), 
            value.name = "Something else"), 
           caption = paste("Some table for: ", class(dta_lst[[i]])))
}
```

When I run the code it produces the desired output (naturally, the provided example makes little sense, in my proper data I melt the data in sensible manner):

---------------------------
 variable   Something else 
---------- ----------------
   mpg            21       

   mpg            21       

   cyl            6        

   cyl            6        

   disp          160       

   disp          160       

    hp           110       

    hp           110       

   drat          3.9       

   drat          3.9       

    wt           2.62      

    wt          2.875      

   qsec         16.46      

   qsec         17.02      

    vs            0        

    vs            0        

    am            1        

    am            1        

   gear           4        

   gear           4        

   carb           4        

   carb           4        
---------------------------

Table: Some table for:  data.frame


----------------
 Something else 
----------------
      112       

      118       
----------------

Table: Some table for:  ts

When I attempt to knit the code in Rstudio the pander tables do not appear:

absent tables

Naturally, without the loop the pander command works just fine and generates the tables that are neatly knitted into a HTML document.


Solution

  • In the for loop there is not 'output screen' unless you use the print(x) function.

    for (i in 1:4) { i } does not display anything

    for (i in 1:4) {print(i)} displays the Numbers 1 2 3 and 4

    Solution: In the FOR loop construct the table (using knitt) and assign it into a variable. Then print out this variable using print() function. Remember. You Must add blank lines after and before the var table: use paste function inside print()