Rnotebook not showing code output for data frames - r

My code chunk output in Rnotebook is not appearing (as if not being run) when I try to view data frame results. I have to pass it through the pander() function to see the output print out. Is this something to do with knitr? I mention this because I set the options at the beginning to the following:
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo = TRUE, eval = TRUE)
```
I have tried setting the options directly in the chunk but get the same unwanted result. Is there a setting I am not configuring correctly? I have to also mention that this is a behaviour that has been somehow inconsistent. That is, I may stop working on it and some time later the code output comes up somehow.
Here's an sample of the work code I am trying to run to copy paste into Rnotebook.
Setting the notebook workspace options
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo = TRUE, eval = TRUE)
```
Loading the corresponding libraries and packages
```{r}
library(easypackages)
libraries("dplyr",
"ggplot2",
"caret",
"tidyverse",
"tidytext",
"ROCR",
"pander",
"knitr",
"broom")
```
Here's some sample data:
```{r}
library(readr)
attibm <- read_csv("https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/datasets/mtcars.csv",
col_types = cols(Attrition = col_character()))
```
Seeing the structure. (This output is shown as expected)
```{r}
glimpse(attibm)
```
Preview the first ten rows (this is the output that doesn't show. Nothing happens)
```{r}
head(attibm)
```
This output doesn't show either. (Nothing happens)
```{r}
attibm %>%
summarise_if(is.integer, mean)
```
When I pass the pander function THEN it is shown.
```{r}
attibm %>%
summarise_if(is.integer, mean) %>%
pander()
```
This one is shown too
```{r}
pander(head(attibm))
```
I have checked the question posted: Output of numbers in R notebook, but I wasn't able to see the connection with this case.
I hope this is clear enough and that you can reproduce the code shown here. Any help on this issue will be highly appreciated.

The newest version of markdown is no longer compatible with pandocv2.
You can check your version of pandoc using
library(rmarkdown); pandoc_version()
If it's pandoc version you need the development version of markdown that you can download there
library(devtools); install_github("rstudio/rmarkdown")
To narrow down the issue of whether this is a problem with the newest version of pandoc, try checking wether the .md produced is correct by adding
---
output:
html_notebook
keep_md: true
---

I had a similar problem which data.frame and DT:data.table wouldn't show any output.
this post helped me.
I found that the cause of problem was my mis-typing in .rmd file name including a non-ASCII character! as soon as i removed it the problem resolved.
Hope this helps others too

Related

How to insert an image from a url into R markdown html vignette?

Similar questions have been asked before about inserting an image from a url (for example here and here ). However, I can't seem to get those solutions to work for me.
I am trying to create an R package vignette and a github.io vignette page. Initially I was saving my images to my machine and when building the vignette I was calling them locally via:
knitr::include_graphics("file/path/image.png")
However, when I use devtools::build_site() to build the github.io site, the images are understandably missing from the vignette. I have uploaded all the images to my GitHub repo and I was wondering if there is any way to display to these images when building the GitHub.io site?
I have tried the following but neither have worked. I just get a blank space where the image should be.
<center><src="https://github.com/tidyverse/ggplot2/blob/main/icons/coord_cartesian.png"></center>
```{r out.width="100%"}
url <- "https://github.com/tidyverse/ggplot2/blob/main/icons/coord_cartesian.png"
knitr::include_graphics(url)
```
My YAML looks like this:
---
title: "myPackage"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{vivid}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
editor_options:
chunk_output_type: console
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "vig/"
)
options(rmarkdown.html_vignette.check_title = FALSE)
```
I figured out the solution to my problem from this. I needed to use the "raw" absolute link from the image. So in the example above, I should have used:
```{r out.width="100%"}
url <- "https://raw.githubusercontent.com/tidyverse/ggplot2/main/icons/coord_cartesian.png"
knitr::include_graphics(url)
```

Getting flextable to knit to PDF

I feel like I've gone down a rabbit hole when all I want is some nice tables in my pdf. Long story, here goes:
I want to print some tables to a PDF from r markdown. I usually use Kable and it works fine. That being said, this table is going to have some really long values, and an unknown number of columns that get generated, and I was having a hard time specifying which column would be what width when I didn't know yet in kable. Anyhow, that led me to flextable.
When I knit to html, the table looks great, like so:
But I'm having trouble knitting to pdf. I understand, via other stack answers, that flextable's need to be saved as images to be plotted to pdf. So I have code like this:
ft <- flextable(x)
ft <- autofit(ft)
tf <- tempfile(fileext = ".png")
## Not run:
if( require("webshot2") ){
save_as_image(x = ft, path = "myimage.png")
}
plot(tf)
But at first it gave me the error that I didn't have the webshot2 package, so after some trouble I installed that (it didn't line up with my version of R (I'm on rstudio.cloud) and then when I try to run it now, it says
Am I missing something obvious? How do I save a flextable as an image and then plot it in my pdf?
I've also tried Joanna's solution here: Is it possible to generate the RTable (FlexTable) in pdf with RMarkdown? and r tells me could not find function "as.html". Even though both flextable and htmltools have been loaded.
P.s. providing reproducible data would be very long given all the code that generates the tables and the fact I need it to knit into a pdf, will provide rstudio.cloud link if anyone is interested
You can now produce PDF without the need of webshot package (flextable >= 0.6.0):
---
title: "Untitled"
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(flextable)
```
```{r}
ft <- flextable(head(airquality))
ft <- autofit(ft)
theme_vader(ft)
```

Selectively knitting R notebook

I would like to make long, well documented R-studio notebooks to completely document analyses, but then be able to knit either the full notebook or an abbreviated version for reports for different audiences. The long version for scientists and a short version as an executive summary.
I know about not running individual chunks, but is there a way to specify chunks together with sections of supporting text to be knit or not, and then somehow turn on or off the selective knitting?
This question shows how to use knit_exit() to exit knitting early, but I am looking for a way to go in and out multiple times through a document.
You can try the following code:
---
title: study sample
output: pdf_document
---
```{r beginning, echo = FALSE, include = FALSE}
echoaudience <- c("scientific", "executive")
```
```{r data1, echo = any(c("scientific","tested") %in% echoaudience)}
# a detailed report
```
```{r data2, echo = any(c("executive","brief") %in% echoaudience)}
# a brief summary
```
```{r data3, echo = any(c("myleftover","brief") %in% echoaudience)}
# some data only in my interest
```
It will return only the code you want to show, in this case data1 and data2. You can control the outputs.
```r
# a quite detailed info
```
```r
# a brief summary
```
Hope it helps.
Regards,
Alexis

Rmarkdown PDF with kableExtra in RStudio Cloud

I'm trying to compile a PDF document from RStudio Cloud, using rmarkdown as the following minimal (not) working example.
First, to be able to install some latex packages (not included in MWE) I had to install tinytex with option force = TRUE. Now if I run the command pdflatex --version I see this result:
pdfTeX 3.14159265-2.6-1.40.19 (TeX Live 2018)
MWE is just below and if I try to knit it from my RStudio Cloud session I get this error:
! Use of \#startpbox doesn't match its definition.
\#startpbox {l>{\raggedright \arraybackslash }p{12cm}l}
l.101 ...{l>{\raggedright\arraybackslash}p{12cm}l}
Error: Failed to compile MWE.tex. See MWE.log for more info.
Execution halted
---
output:
bookdown::pdf_book:
toc: false
keep_tex: true
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r start, include = FALSE}
library(tibble)
library(magrittr)
```
```{r table, results = "asis"}
tbl <- tribble(~number, ~descrip, ~perc,
"8415", "long long very long description of something. More text and stuff here.", "10%")
kableExtra::kable(tbl,
booktabs = TRUE,
longtable = TRUE,
col.names = c("NCM", "Description", "IPI%")) %>%
kableExtra::kable_styling(full_width = FALSE) %>%
kableExtra::column_spec(2, width = "12cm")
```
The funny thing is, in my local R session, I can compile this without a problem, although I'm using TeX Live 2017 installed manually.
Does anyone know what's happening here? I know it's a Latex problem, but somehow it's the interaction of knitr (or pandoc?) and kableExtra that is causing some sort of conflict.
Thank you very much!

How to show code but hide output in RMarkdown?

I want my html file to show the code, but not the output of this chunk:
```{r echo=True, include=FALSE}
fun <- function(b)
{
for(a in b)
{print(a)
return(a * a)}
}
y <- fun(b)
```
When I run the code, i need the print to see the progress (it is quite a long function in reality).
But in the knitr file, I use the output in a further chunk, so I do not want to see it in this one (and there's no notion of progress, since the code has already been run).
This echo=True, include=FALSE here does not work: the whole thing is hidden (which is the normal behavior of include=FALSE).
What are the parameters I could use to hide the prints, but show my code?
As # J_F answered in the comments, using {r echo = T, results = 'hide'}.
I wanted to expand on their answer - there are great resources you can access to determine all possible options for your chunk and output display - I keep a printed copy at my desk!
You can find them either on the RStudio Website under Cheatsheets (look for the R Markdown cheatsheet and R Markdown Reference Guide) or, in RStudio, navigate to the "Help" tab, choose "Cheatsheets", and look for the same documents there.
Finally to set default chunk options, you can run (in your first chunk) something like the following code if you want most chunks to have the same behavior:
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = T,
results = "hide")
```
Later, you can modify the behavior of individual chunks like this, which will replace the default value for just the results option.
```{r analysis, results="markup"}
# code here
```
The results = 'hide' option doesn't prevent other messages to be printed.
To hide them, the following options are useful:
{r, error=FALSE}
{r, warning=FALSE}
{r, message=FALSE}
In every case, the corresponding warning, error or message will be printed to the console instead.
```{r eval=FALSE}
The document will display the code by default but will prevent the code block from being executed, and thus will also not display any results.
For muting library("name_of_library") codes, meanly just showing the codes, {r loadlib, echo=T, results='hide', message=F, warning=F} is great. And imho a better way than library(package, warn.conflicts=F, quietly=T)
For completely silencing the output, here what works for me
```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({
# Your code here
2 * 2
# etc etc
})})
```
The 5 measures used above are
error = FALSE
warning = FALSE
message = FALSE
invisible()
capture.output()
To hide warnings, you can also do
{r, warning=FALSE}

Resources