Is there an R script that write rmd files with the content from excel spreadsheets?

Viewed 93

Solution in comments!

I'd like to have a template for the rmd file and have the template filled in with content, both R code chunks and regular text, according to the content of the spreadsheet.

Content to be used in code chunk Text to be pasted after code chunk
Parametrized code 1 Description of event 1
Parametrized code 2 Description of event 2

Rmd output:

"""{r, echo = FALSE, comment = NA}

set.seed(rand_seed)

parametrized code 1

"""

Description of event 1

Thanks for your help!

2 Answers

I don't know if such a tool is available as of yet. However, you may be interested in taking a look at this topic https://bookdown.org/yihui/rmarkdown/parameterized-reports.html, from the R Markdown Definitive Guide.

EDIT: Well, I came up with a simple solution. I'm not sure of how big your needs are for this logic, but for only a handful of chunks, maybe this script could help you. I tested it and it works.

instructions_set <- data.frame(
  code_chunks <- c(
    "a <- 50; print(a)",
    "hist(iris$Sepal.Length)"
  ),
  text_chunks <- c(
    "I've just set the variable a to 50 and printed it.",
    "This is a histogram of the variable Species in the Iris dataset."
  )
)

file <- apply(instructions_set, MARGIN = 1, function(x) {
  x[1] <- paste0("```{r}\n", x[1], "\n```")
  return(
    paste(x[1], x[2], "", sep = "\n")
  )
})

readr::write_file(purrr::reduce(file, paste0), "test_file.Rmd")

I've found a solution using the knitrdata package. You can use the create_chunk and insert_chunk functions to convert strings to code chunks for rmarkdown.

My next step would be to load the strings into a data frame and iterate these two functions over the content of the data frame to create and insert multiple code chunks to the rmd file.

For the text part of the Rmd file, I'd use the writeLines function.

Here's a sample of the code chunk creation code I've put together:

library(knitrdata)
library(svDialogs)

#choose the blank template Rmd.file

input_file <- dlg_open(message = "Please select the blank Rmd file to use a template!" )$res

output_file <- paste(as.character(dlg_input( message =  "Please name your output file!")$res), ".Rmd", sep = "")

#select line at which to insert the code chunk - I've chosen then last line of the file

insert_at <- length(readLines(input_file))

#takes string input and formats it as a chunk then returns it as a character vector

input_chunk <- create_chunk(text = "print('this is a test')", chunk_label = "Testing label creation", chunk_type = "r")

#inserts properly formatted chunk at the specified line of lines read from the target Rmd file

rmd_text <- insert_chunk(input_chunk, line = insert_at , rmd.file = input_file )

#since insert_chunk returns a character vector, this line writes it to a new Rmd file

writeLines(rmd_text,output_file)

Related