Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R, using Knitr to view a table in HTML

Tags:

r

knitr

I feel like I am making this more difficult than it is. All I need to do is make a table from my .csv document and then Knit it to show up in an HTML document and ioslides presentation. I am working in RMarkDown in RStudio. The start of the code is just this:

```{r echo=FALSE, results='hide',message=FALSE}    
DF <- read.csv('DF.csv', header = TRUE)
```

Where my data is something like this (but as a .csv):

     Animal  num1  num2 
0    22      36.6   213      
1    39      42.44  141      
2    40      39     157

And I have tried things like:

```{r}
DF
```

But that just throws all the data onto a slide without putting it into a table. When I try things such as

```{r table2, results='asis', message=FALSE} 
print(xtable(head(Df))) 
```

Or:

```{r table2, results='asis', message=FALSE} 
data.table(DF)
```

It runs fine when I just run the lines in R but as soon as I try to run Knitr it comes up with the error message "Error in eval(expr, envir, enclos): could not find function "data.table" Calls: handle-> withCallingHandlers -> withVisible -> eval-> eval Execution halted". So I thought maybe I had to covert the table to a markdown document and then I could Knit it. Such as:

```{r table2, results='asis', message=FALSE} 
kable(head(DF), format = "markdown")
```

No such luck though, clicking Knitr just ran it to that line with an error message of: ""Error in eval(expr, envir, enclos): could not find function "kable" Calls: handle-> withCallingHandlers -> withVisible -> eval-> eval Execution halted". Does Knitr not recognize these functions or am I just going about this completely wrong. I want the table to look like this:

table

like image 913
Michael Avatar asked Mar 23 '15 20:03

Michael


People also ask

How do I embed a table in R Markdown?

To use it, open a Rmd or R document and select “Addins –> Insert Table”.

How do you use the knitr in RStudio?

If you are using RStudio, then the “Knit” button (Ctrl+Shift+K) will render the document and display a preview of it.

What is knitr :: Kable?

The kable() function in knitr is a very simple table generator, and is simple by design. It only generates tables for strictly rectangular data such as matrices and data frames.


1 Answers

You need to include the libraries. What I do is create an invisible chunk like so:

```{r include=FALSE}
library(pander)
```

I recommend PANDER which will produce a table like the one in your screenshot

```{r, comment=NA}
pander(DF, type = 'grid')
```
like image 184
Ken Yeoh Avatar answered Sep 28 '22 15:09

Ken Yeoh