Reputation: 297
The question if needs further elaboration is this. 1. A rmd file is written 2. Rmd is knitted to html. 3. Html is saved with the code in it. I need Rstudio to read the Html file, identify the code inside it and run it. Is there a way?
Upvotes: 1
Views: 81
Reputation: 78832
Assuming:
---
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
Blah Blah
```{r cars}
summary(cars)
```
```{r pressure, echo=FALSE}
plot(pressure)
```
```{r}
xdf <- rbind.data.frame(mtcars, mtcars)
library(tidyverse) # rly bad place to put this but it's just a demo
just6 <- filter(xdf, cyl == 6)
```
```{r}
ggplot(mtcars, aes(wt, mpg)) + geom_point()
```
```{r}
count(just6, gear)
```
and a file named "forso.Rmd" which is knit to "forso.html":
library(rvest)
pg <- read_html("forso.html")
html_nodes(pg, "pre.r") %>%
html_text() %>%
styler::style_text() %>%
write_lines("my-recovered-r-code.R") %>%
cat(sep="\n")
## summary(cars)
## xdf <- rbind.data.frame(mtcars, mtcars)
##
## library(tidyverse) # rly bad place to put this but it's just a demo
## just6 <- filter(xdf, cyl == 6)
## ggplot(mtcars, aes(wt, mpg)) + geom_point()
## count(just6, gear)
The "##
" above is just an artifact of the output.
NOTE that you will not be able to get include=FALSE
or echo=FALSE
code back (as the above demonstrates).
Also NOTE that the use of styler
is 100% optional.
Upvotes: 3