Creating Scripts from a Template in Julia - julia

I have a text file - it's a template that I want to alter and save as a another file (in this case a markdown file, but it doesn't matter):
my_test.txt:
---
title: My report
---
$my_var
As you can see there is a placeholder $my_var - I want to read in the file as a string and then put it the value of the variable my_var. How can I do this?
I already tried several things around this:
using Chain
my_var = "some string"
#chain begin
read("my_test.txt", String) # read the text file as a string
"\"\"\"" * _ * "\"\"\"" # wrap the string with triple quotes
Meta.parse # parse...
eval # ...and eval
write_to_file("reports/jmd_files/org_$(org_id).jmd") # write it to a markdown file
end
It does not work though. I tried a lot of variants and I either get an error saying my_var does not exist or the value that gets inserted is nothing (which is not what it is supposed to be.
So, it really seems to be about the environment in which this is executed, but I can't figure out what the problem is.
It shouldn't be important, but just to be sure - eventually want this to run in a loop or in a (to-be-broadcasted) function. So, hard-coding for the single example would not really be a solution.

It seems you're looking for a text templating engine like Mustache.jl. Eg:
using Mustache
function createscript()
vars = Dict("my_var" => "some string")
# Doesn't have to be a Dict - see the docs for other
# options eg. a module name can be passed
# to grab variables from it
open("data/rendered.jmd", "w") do out
render(out, read("data/reporttemplate.mustache", String), vars)
end
end
with reporttemplate.mustache containing:
---
title: My report
---
{{my_var}}
Using a text-templating engine is a lot safer and less error prone than an eval.

Not actually an answer to your question but.. are you sure you want to do it ? What you are describing looks like creating a dynamic document, but there are already lots of packages for that.
For example, Documenter.jl and Weave.jl both take markdown documents with embedded Julia scripts and are designed to run the document and compile it in HTML or PDF pages showing the script or its outputs (you choose).
I prefer going a step further and I start from a (valid) Julia script where the markdown structure is embedded with an extra comment layer (e.g. # ## This would be an H2 header) and then use Literate.jl to transform it to a markdown with embedded Julia and Documenter.jl to create a navigable web site.
These packages have plenty of options and integrate easily with CI like GitHub actions.

Related

R Markdown: output with weird characters

I am seeking your help as I encountered a curious R markdown issue when using scripts sourced from external. My rmd. file contains several code chunks that generate tables. For some of the chunks, they work very well with scripts sourced from external, for example:
source(
here::here("file_name_1",
"file_name_2",
"file_name_3",
"file_name_4",
"*********.R"),
echo = FALSE,
print.eval = TRUE
)
However, some chunks with external script sourced using exactly the same code template as above do not give me the output (which is a table).
I ended up re-editing the source script and rmd file. First, in the script, I assigned the table with a name, e.g., Table_1 <- [codes that generate the table] . Second, in the rmd file, I added Table_1 below the code chunk to call the table generation function. For example:
source(
here::here("file_name_1",
"file_name_2",
"file_name_3",
"file_name_4",
"*********.R"),
echo = FALSE,
print.eval = TRUE
)
Table_1
Then I re-run the rmd, it seemed like starting to work and did give me a table that I want, but there were minor issues: some characters / signs in the table were weird. For example, 1-18 became 1–18.
Any ideas / hints for solving this problem from you would be very much appreciated.
It turns out that the "call function" do work. The reason why 1–18 became 1–18 is because the dash "–" came from non-standard keyboard or Copy-Paste, which can not be recognised in regular R script. However, theses special characters can be recognised in R Markdown.

R Markdown - adding an automatic macro to an MS-word document

I am currently generating word documents with Rmarkdown. But the formating is a bit difficult compared to an HTML output. One of the technical solution I could use would be to add a macro on my word file and make it execute automaticaly on opening.
The following macro should do the trick for automatic execution :
Sub Auto_Open()
Msgbox "Hello World!"
End Sub
How would one adds this macro to the doc knitted with Rmarkdown ? How do one make sure it executes correctly on opening ?

Parse YAML front matter with R

I want to use YAML for SAS program documentation in a manner similar to how R studio uses YAML. Can I put YAML at the top of my program, then read it into R as some object? The program file would just be a text file called program_1.sas. There would be a bunch of these in a directory or two.
I can then use the object in an R notebook to produce a readable document describing a set of SAS programs. I would have to find a function to display the object in a readable format.
I noticed that this issue is addressed for languages like python and JAVA, but I am hoping to do it in R. Obviously this code has already been written. For example the function yaml_front_matter must do this, but it does not seem to be documented.
If I could also write/change the YAML header that would be a big plus.
Here is an example:
Project: Disease Burden
Directory: /net1/program/
Purpose: Extract Data
The only extra piece is that I would have to comment out this header and also identify it
/*
---
Project: Disease Burden
Directory: /net1/program/
Purpose: Extract Data
---
*/
I could then create markdown like this
# Project: Disease Burden
Directory
: /net1/program/
## Purpose
Extract Data

show text from a Rmd file using purl function in another Rmd file

I have a Rmd file with some chunks and some text. How can I add the output (including text) in from that file to another Rmd file, calling the first one with purl or something similar?
Thanks
There are a few ways to go about this. The better approach, I believe, is to create a "child" Rmd page which is conditionally executed. I use this regularly to minimize the amount of report code I maintain. You don't provide a code example, but here is a process in one of my reports which executes two different Rmd's depending on the the condition:
```{r conditional, child = if (override == "report") 'leaflet_child.Rmd' else 'footer.Rmd'}
```
As far as your perl code, I would place that in one of the child .Rmd's to be executed if condition==T. Also, note that the child page execution chunk should do that and only that: execute one or another .Rmd. If you add additional commands in that chunk it will throw warnings.
These conditions can also be passed via commandArgs, as with this example from my project make file which passes the "now" argument, which then conditionally executes certain Rmd files:
Rscript $(R_OPTS) -e "rmarkdown::render('putyourscripthere.Rmd')" now
This is picked up within the Rmd via something like this, which sets a default value in the event of a null commandArg:
# Command arguments
if(length(commandArgs(trailingOnly=TRUE)>0)) {
override <- commandArgs(trailingOnly=TRUE)
} else {
override <- "report"
}
Another approach which is much "hacky-er" is to use sed or awk to extract text from a document and pipe it into a new .Rmd file. I would only take this approach as a last resort and there are plenty of examples with a basic Google search for Sed or Awk. Best, Derek

Displaying png files from R into spotfire

I want to pass data from Spotfire to R and then display the plot constructed by R.
What is the best way to do this?
I’ve figured out the trick of putting images into Spotfire. It’s not hard if you follow these directions, but it’s done in a way very different from how you guess you would do it in Spotfire, and that’s why it took me awhile to figure out.
Here’s an overview of how to do it. You create a DocumentProperty which is a binary object, you write some Spotfire code that gives a value to that Document Property, and you display that binary object using a Spotfire Property Control of the “Label” type.
The confusing parts are that you DON’T use the Spotfire “Insert Image” tool at all, and that you DON’T use the filename generated inside the R code in Spotfire at all. Once you get used to the idea that the two most obvious ways you think you would approach the problem in Spotfire are entirely useless and wrong, you can make some progress.
I’ll leave out the spiderplot specifics because the code’s pretty long.
Here’s what you do.
1) Create a document Property in Spotfire of type “Binary”, e.g., “imageThatGoesBackToSpotfire”
2) You write some R code that generates an image and writes it to a file:
# get a temporary directory name on the local machine. You wouldn’t need to do this is you were just
# going to run it on your own, but you need to do it if you intend to let anybody else run it on their own machine.
tempfilebase = tempfile()
# take the tempfilebase and prepend it to a filename.
myFilename<-“someFileName.jpg”
myFullFilename <- paste(tempfilebase,myFilename,sep="")
#open a jpeg
jpeg(filename=myFullFileName)
# generate the image, however you normally would in R
plot(input)
# close the file
dev.off
# open a connection to that file.
myConnection<-file(myFullFileName,open=”rb”)
imageThatGoesBackToSpotfire<- data.frame(r=readBin(myConnection, what="raw", n=(file.info(myFullFileName)$size)))
close(myConnection)
3) Run your R script, above. Select some columns that are the “input” to the plot, and make the R script return outputs to the “imageThatGoesBackToSpotfire” DocumentProperties.
4) Create a text area in Spotfire.
5) Insert a Property Control into the text area of type “label”. (Click on the icon that’s circled in the picture below). This opens a dialog,
You need to register a data function with inputs and outputs, and the specific PNG data needs to be returned as a binary label.
Some details: http://spotfire.tibco.com/tips/2014/02/25/dynamically-displaying-images-in-a-text-area/

Resources