How to write an R program that copies its source code to a file? - r

I'm writing an R script whose contents can change from time to time. It would be really helpful if I could insert a command that would copy the current contents of the script to a file, so I can go back later and see exactly what commands I executed during that run of the code.
How can I do this?

You can do this with the teaching demos package:
install.packages("TeachingDemos")
library(TeachingDemos)
#Will write to a file in the working directory
txtStart("captureCode.txt")
#This comment will not appear in the file, all commands and output will
Sys.Date()
#This command ends writing to the file
txtStop()
Source

Related

Understanding R console vs writing R code in text file

What is the difference between using R console vs writing R code in a text file? I wrote this question on Kaggle but there were no previous questions on this matter.
When you supply code via text file (.R file) you "run the file with R" without visualizing it and it can stop somewhere due to error i.e. (which can be handled, etc.). Also running an .R file with R (for example via .bat file) generates a .Rout file, which is basically a print out of the console and some aditional info like runtime, etc.
If you feed the code in the console, each line is treated independently: even if there is an error you can process an aditional line (if it depends on the failed comand then it will fail also though) and you get to see each result as soon as the comand is run. In comparision to the .R file you will have no copy of the code other than that stored in the session - meaning you will end up needing to save to disk the code you have written if you want it to persist between session. Now you can choose to use whatever text format you like for this task from simple .txt to .docx BUT if you use .R format you can manipulate with notepad++ or the notepad editor and still run/complipe the file with R (via .bat file for example). In case of opting against .R file to store the written code, you will have to feed it to the console again to run.
In R Studio you can open .R files and manage (extend, correct) your code and feed it comand per comand or as a block to the console. So one could say you use .R files to manage you code, having the possiblity to compile/run these .R files directly with R to execute on a button click or repeatedly for example.
Not sure if that is what you are looking for?

Output of saved .R files in r

I want to save my code in R. I did:
save(Data,file="Code_Data.R")
When I open the file in R again, the code looks like hieroglyphics.
How can I save the code in a way, that I can read the code in an editor or RStudio again?
save outputs a binary copy of the objects you tell it to save, not R code. Because you are naming this file with a ".R" extension, RStudio is blindly trying to open this binary file as R code, and you are seeing the results of that mess.
Technically, the R language doesn't care what the extension of the file is. As long as you know that the file contains, you can load it back in with the command load("Code_Data.R"). However, if you want to get RStudio to recognize that this is actually a file containing binary data and not R code, try saving the file with the canonical ".RData" extension:
save(Data, file="Code_Data.RData")
Using the ".RData" extension will also help you and other programmers who look at your code avoid this confusion in the future.

Calling Skim from inside R

I'm making a simple line in r to automatically open my generated plots.
I output the plots to a file called "plots.pdf" in the same directory as my r file, and at the end i use this two lines to try to open it:
dir <- paste("/Applications/Skim.app/Contents/MacOS/Skim ",getwd(),"/plots.pdf",sep="")
system(dir)
Basically, dir concatenates the full path of the skim app and the full path of the generated plot.
If i run the string stored at dir in a shell it works perfect, it opens the pdf file in Skim, but when i run it with system() from inside R it doesn't work (Skim says 'The document “plots.pdf” could not be opened.').
I believe this is a very little mistake somewhere in the syntax regarding the absolute/relative paths, but haven't managed to find it... Any advice is welcome! (Or a better way to achieve the same)
I found a way to bypass that problem, i just changed the path to Skim for the 'open' command and i let the system to assign the default app for pdf viewing. So:
dir <- paste("open ",getwd(),"/plots.pdf",sep="")
And it works.

How to converge multiple R files into one single file

Situation
I wrote an R program which I split up into multiple R-files for the sake of keeping a good code structure.
There is a Main.R file which references all the other R-files with the 'source()' command, like this:
source(paste(getwd(), dirname1, 'otherfile1.R', sep="/"))
source(paste(getwd(), dirname3, 'otherfile2.R', sep="/"))
...
As you can see, the working directory needs to be set correctly in advance, otherwise, this could go wrong.
Now, if I want to share this R program with someone else, I have to pass all the R files and folders in relative order of each other for things to work. Hence my next question.
Question
Is there a way to replace all the 'source' commands with the actual R script code which it refers to? That way, I have a SINGLE R script file, which I can simply pass along without having to worry about setting the working directory.
I'm not looking for a solution which is an 'R package' (which by the way is one single directory, so I would lose my own directory structure). I simply wondering if there is an easy way to combine these self-referencing R files into one single file.
Thanks,
Ok I think you could use something like scaning all the files and then writting them again in the same new one. This can be done using readLines and sink:
sink("mynewRfile.R")
for(i in Nfiles){
current_file = readLines(filedir[i])
cat("\n\n#### Current file:",filedir[i],"\n\n")
cat(current_file, sep ="\n")
}
sink()
Here I have supposed all your file directories are in a vector filedir with length Nfiles, I guess you can adapt that

Print plain text of help file to console [duplicate]

I'd like to be able to write the contents of a help file in R to a file from within R.
The following works from the command-line:
R --slave -e 'library(MASS); help(survey)' > survey.txt
This command writes the help file for the survey data file
--slave hides both the initial prompt and commands entered from the
resulting output
-e '...' sends the command to R
> survey.txt writes the output of R to the file survey.txt
However, this does not seem to work:
library(MASS)
sink("survey.txt")
help(survey)
sink()
How can I save the contents of a help file to a file from within R?
Looks like the two functions you would need are tools:::Rd2txt and utils:::.getHelpFile. This prints the help file to the console, but you may need to fiddle with the arguments to get it to write to a file in the way you want.
For example:
hs <- help(survey)
tools:::Rd2txt(utils:::.getHelpFile(as.character(hs)))
Since these functions aren't currently exported, I would not recommend you rely on them for any production code. It would be better to use them as a guide to create your own stable implementation.
While Joshua's instructions work perfectly, I stumbled upon another strategy for saving an R helpfile; So I thought I'd share it. It works on my computer (Ubuntu) where less is the R pager. It essentially just involves saving the file from within less.
help(survey)
Then follow these instructions to save less buffer to file
i.e., type g|$tee survey.txt
g goes to the top of the less buffer if you aren't already there
| pipes text between the range starting at current mark
and ending at $ which indicates the end of the buffer
to the shell command tee which allows standard out to be sent to a file

Resources