How to transfer variables to RDCD file with markdown R?

I am trying to create a generic rmarkdown template that will perform analysis on a data frame. I would like to be able to transfer the rmarkdown file in the data frame, and not hardcode it every time.

Below is a snippet that I experimented with. You can see that at the top I have to load the data frame (mtcars). I also manually identify independent variables (ivs) and dependent variables (dvs). I would like to pass them as parameters. I am trying to run a quick and dirty version of SPSS Explore functionality. "Explore.Rmd":

```{r} library(ggplot2) data(mtcars) mtcars$am <- factor(mtcars$am, levels=c(0,1), labels=c("Manual", "Automatic")) df <- mtcars ivs <- c("cyl", "disp", "hp", "drat", "wt", "am", "qsec") dvs <- c("mpg", "qsec") ``` Histograms ------------------------------------- ```{r} for (v in union(ivs, dvs)) { hist <- ggplot(df, aes_string(x=v)) + geom_histogram() print(hist) } ``` 

I would like to have code that looks something like this to generate HTML using knitr or something similar.

 myDF <- read.delim("mydata.tab") ivs <- c("iv1", "iv2", "iv3") dvs <- c("dv1", "dv2", "dv3") magic("Explore.Rmd", myDF, ivs, dvs) # <- how do I do this part? 

So, is it possible to have a static rmarkdown file and pass parameters to it? Or would there be another way to accomplish what I'm trying to do?

+6
source share
3 answers

I think you can use knit2html from the knitr package to do the magic.

  • You define your markup file as follows and save it as mydoc.Rmd

      ```{r} source('test.R') ``` ```{r} library(ggplot2) for (v in union(ivs, dvs)) { hist <- ggplot(myDF, aes_string(x=v)) + geom_histogram() print(hist) } 
  • In test.R you are preparing your data:

     myDF <- read.delim("mydata.tab") ivs <- c("iv1", "iv2", "iv3") dvs <- c("dv1", "dv2", "dv3") 
  • You are compiling with knitr

     Knit2html('mydoc.Rmd') 
+4
source

Another option is to list the variables using params in the rmarkdown::render function, see http://rmarkdown.rstudio.com/developer_parameterized_reports.html .

 rmarkdown::render("MyDocument.Rmd", params = list(df = myDF)) 

Then call the parameters in yaml:

 --- title: My Document output: html_document params: df: myDF --- 

which can then be assigned in the body of the report:

 ```{r} myDF <- params$df ``` 
+7
source

I think the alternative is given at https://github.com/yihui/knitr/issues/567

you will need to create these arguments in advance, for example.

 args='2013' knit('../my.Rmd','test.html') 

then knit() will recognize the arguments inside my.Rmd; if you want to understand the details

in argument envir
+1
source

Source: https://habr.com/ru/post/954311/


All Articles