How to make Rmarkdown carry over sections of code? - r

I have a piece of RMarkdown code that runs fine in one block.
```{r}
library(tidyverse)
data("PlantGrowth")
set.seed(1234)
PlantGrowth %>% sample_n_by(group, size = 1)
levels(PlantGrowth$group)
```
However, if I try to break it into pieces of code, which I need to do in order to add explanations, I get the following error in the RMarkdown console.
```{r eval=TRUE}
library(tidyverse)
data("PlantGrowth")
set.seed(1234)
```
Comment the code here
```{r eval=TRUE}
PlantGrowth %>% sample_n_by(group, size = 1)
levels(PlantGrowth$group)
```
Say more stuff...
Error in PlantGrowth %>% sample_n_by(group, size = 1) : could not find function "%>%" Calls: <Anonymous> ...withVisible -> eval_with_user_handlers -> eval -> eval Execution Halted.
Is there a way to make markdown carry over the libraries and variables loaded in previous code blocks up to the end of the document?

Make sure you insatlled tidyverse and rstatix in your env.
```{r eval=TRUE}
library(tidyverse)
library(rstatix)
data("PlantGrowth")
set.seed(1234)
```
Comment the code here
```{r eval=TRUE}
PlantGrowth %>% sample_n_by(group, size = 1)
levels(PlantGrowth$group)
```

Related

R Markdown Presentation: showing one plot in each slide

I have a list of 300 plots and want one PowerPoint slide to show one plot (300 slides). What's the best way to achieve this?
A toy example using the built-in iris dataset to create a list of plots:
purrr::map(names(iris[,-5]), function(col_name){
plot = iris %>%
ggplot(aes(x = !!as.name(col_name))) +
geom_histogram()
return(plot)
})
I hope to create PowerPoint slides with one plot on each slide.
I will be using the iris data set, which is a built-in data set often used to populate example code.
With the following code in a Rmd file:
---
title: "Test_PowerPoint"
author: "KoenV"
date: '2022-06-30'
output: powerpoint_presentation
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r include=FALSE, warning=FALSE, message=FALSE}
library(tidyverse)
library(purrr)
```
```{r, iris, fig.cap="A scatterplot.", echo=FALSE, warning=FALSE, message=FALSE}
## your code
purrr::map(names(iris[,-5]), function(col_name){
plot = iris %>%
ggplot(aes(x = !!as.name(col_name))) +
geom_histogram()
return(plot)
})
```
And after hitting the "knit" button, you will see a PowerPoint presentation appearing, with the following lay-out:
Please let me know, whether this is what you wanted.

Assign figure caption to html widget (vtree package) in R markdown output

I need to implement a figure caption in a plot that is generated by the vtree package in R markdown. I learned that this is a htmlwidget and figure captions should now be possible for htmlwidgets used in R markdown with install.packages('webshot') and webshot::install_phantomjs() (reference: https://bookdown.org/yihui/bookdown/html-widgets.html#ref-R-DT.
But days after I am not really any step further. I did not find any example (show case) for this issue (fig.cap for htmlwidgets in R markdown in the net) so my hope is that someone out there can give me some help!
In my iris dataset example, in Fig. 1 the caption is not working in contrast to Fig. 2.
my iris set example RMD file:
YAML
---
title: "test"
author: "TJ"
date: "14 12 2020"
output: html_document
---
code chunk 1: load libraries and data
knitr::opts_chunk$set(echo = TRUE)
library(vtree)
library(webshot)
library(tidyverse)
attach(iris)
df <- iris %>%
select(Species) %>%
cbind(sapply(levels(.$Species), `==`, .$Species))
code chunk 2: Figure 1
{r fig1, echo=FALSE, fig.cap="Vtree plot"}
vtree(iris, "Species")
code chunk 3: Figure 2
{r fig2, echo=FALSE, fig.cap="Scatter plot iris dataset"}
plot(Sepal.Length, Sepal.Width, main="Scatterplot Example",
xlab="Sepal Length ", ylab="Sepal Width ", pch=19)
There is a workaround using the Magick package.You save the image as .png using grVizToPNG (make sure you comment this line out before you render your document or put it in a separate chunk with ยด{r eval = FALSE}, otherwise you will get an error during rendering:
```{r eval=FALSE, echo = FALSE}
myimage <- vtree(iris, "Species")
saveMyimage <- grVizToPNG(myimage, width=800)
```
Here you use the Magickpackage:
```{r magick, echo= FALSE}
MyimagePNG <- image_read("myimage.png")
image_annotate(MyimagePNG, "Vtree plot", size = 35, gravity = "southwest")
```

Remove the output of the garbage collector gc() in Rmarkdown

I have a Rmarkdown document where the garbage collector is used to save memory during renderization. The function gc() is called at the end of some code chunks for convenience, but I would like to hide its output, while showing other code in the same chunk (e.g. a plot). If this output is impossible to hide without using eval=FALSE or include=FALSE (eg. with gc() in a separate chunk), then I would like to understand why, and if this might happen for other functions as well.
Example code to reproduce the problem is given below:
---
title: "Example"
output:
html_document
---
```{r, message=FALSE, warning=FALSE, echo=FALSE}
library("tidyverse")
```
```{r, message=FALSE, warning=FALSE, echo=FALSE}
df <- mtcars %>% dplyr::group_by(cyl) %>% dplyr::summarise(meanMPG = mean(mpg))
df %>% ggplot() + geom_point(aes(x=cyl, y=meanMPG))
rm(df); gc(verbose = FALSE, full = FALSE)
```
EDIT: as you can note, the problem persist even when the options verbose=FALSE and full=FALSE are used in gc().

Remove progress bar from knitr output

I'm analyzing some data and would like to do a Simpsons paradox on R. I've installed the Simpsons package and loaded the library. Here is an example based on the package documentation:
---
output: html_document
---
```{r}
library(Simpsons)
#generating data
Coffee1=rnorm(100,100,15)
Neuroticism1=(Coffee1*.8)+rnorm(100,15,8)
g1=cbind(Coffee1, Neuroticism1)
Coffee2=rnorm(100,170,15)
Neuroticism2=(300-(Coffee2*.8)+rnorm(100,15,8))
g2=cbind(Coffee2, Neuroticism2)
Coffee3=rnorm(100,140,15)
Neuroticism3=(200-(Coffee3*.8)+rnorm(100,15,8))
g3=cbind(Coffee3, Neuroticism3)
data2=data.frame(rbind(g1,g2,g3))
colnames(data2) <- c("Coffee","Neuroticism")
example <- Simpsons(Coffee,Neuroticism,data=data2)
plot(example)
```
This is returning a plot with 3 clusters (exactly what I need). However, when I Knit the Rmd file to HTML, I'm getting a lot of equals signs (======) with a percentage next to it like a loading grid which I would like to remove from my final output.
You can suppress any output messages in R by setting the knitr chunk option. If we wish to hide all code output other than plots, we can use the following solution:
---
output: html_document
---
```{r echo=FALSE, results='hide', fig.keep='all', message = FALSE}
library(Simpsons)
#generating data
Coffee1=rnorm(100,100,15)
Neuroticism1=(Coffee1*.8)+rnorm(100,15,8)
g1=cbind(Coffee1, Neuroticism1)
Coffee2=rnorm(100,170,15)
Neuroticism2=(300-(Coffee2*.8)+rnorm(100,15,8))
g2=cbind(Coffee2, Neuroticism2)
Coffee3=rnorm(100,140,15)
Neuroticism3=(200-(Coffee3*.8)+rnorm(100,15,8))
g3=cbind(Coffee3, Neuroticism3)
data2=data.frame(rbind(g1,g2,g3))
colnames(data2) <- c("Coffee","Neuroticism")
example <- Simpsons(Coffee,Neuroticism,data=data2)
plot(example)
```
I would note that this package seems to print out a lot more content that most packages, and therefore the combination of options are quite long.
An easier method would probably be to move the plot to a separate chunk and have all the analysis run before it. The include argument can be used to suppress all outputs, but this includes plots, hence why we must use two chunks:
```{r, include = FALSE}
# your code to build model
```
```{r}
plot(example)
```
Check out the full list of knitr chunk options here

R markdown doesn't find object

I am using R markdown to knitter my codes into a word document
I am pretty new to R as well as to R markdown
I have the following code :
{r, eval=TRUE, fig.height=7, fig.width=5, message=FALSE, warning=FALSE}
lifeExpectancy <- rename(lifeExpectancy, Incomegroup= WORLDBANKINCOMEGROUP)
plife <- ggplot(lifeExpectancy, aes(x= LifeExpectancy))
plife1 <- plife + geom_histogram(fill="white", aes(color= Incomegroup))
plife1 <- plife1 +facet_grid(SEX~Incomegroup) + xlab("average life
expectancy")
plife1
this is the warning message it returns :
Quitting from lines 32-38 (Termpaper_Franziska.Rmd)
error in rename_(.data, .dots = lazyeval::lazy_dots(...)) :
Object 'lifeExpectancy' not found
calls : <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval
> rename -> rename_
stopped`
What I already did :
I set the working directory correctly for R markdown as well as for my original script
I used
{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_knit$set(root.dir =
"C:/Users/Maxi/Desktop/PrettyPlots2016/Termpaper")
to set the working directory but that didn't help either.
Last but not least I also set
eval=FALSE
but then I didn't get my plot of course, which didn't help me either.
If anyone has a solution for my dilemma I would be very happy to hear it !
Thank you a lot !

Resources