Align two data.frames next to each other with knitr?

前端 未结 2 1620
天涯浪人
天涯浪人 2020-12-06 12:26

I\'m new to knitr (and also quite new to R), so this might be a dumb question...

I have two data.frames, which both have two columns, but different numbers of rows.

相关标签:
2条回答
  • 2020-12-06 13:08

    The development version of knitr (on Github; follow installation instructions there) has a kable() function, which can return the tables as character vectors. You can collect two tables and arrange them in the two cells of a parent table. Here is a simple example:

    ```{r two-tables, results='asis'}
    library(knitr)
    t1 = kable(mtcars, format='html', output = FALSE)
    t2 = kable(iris, format='html', output = FALSE)
    cat(c('<table><tr valign="top"><td>', t1, '</td><td>', t2, '</td><tr></table>'),
        sep = '')
    ```
    

    You can also use CSS tricks like style="float: [left|right]" to float the tables to the left/right.

    If you want to set cell padding and spacing, you can use the table attributes cellpadding / cellspacing as usual, e.g.

    ```{r two-tables, results='asis'}
    library(knitr)
    t1 = kable(mtcars, format='html', table.attr='cellpadding="3"', output = FALSE)
    t2 = kable(iris, format='html', table.attr='cellpadding="3"', output = FALSE)
    cat(c('<table><tr valign="top"><td>', t1, '</td>', '<td>', t2, '</td></tr></table>'),
        sep = '')
    ```
    

    See the RPubs post for the above code in action.

    0 讨论(0)
  • 2020-12-06 13:11

    Would you settle for "an image" of data.frames? Clearly my solution is crude, feel free to fiddle with the details (spacing between data.frames, for example).

    Two data.frames, side by side
    ========================================================
    
    ```{r}
    library(gridExtra)
    x <- data.frame(a = runif(5), b = runif(5))
    y <- data.frame(a = runif(7), b = runif(7))
    
    grid.arrange(tableGrob(x), tableGrob(y), ncol = 2)
    ```
    

    enter image description here

    0 讨论(0)
提交回复
热议问题