Getting .Rprofile to Load at Startup - r

I have a global ~/.Rprofile file and another .Rprofile file located in my project's current working directory and both of the have the following contents:
.First() <- function() {
options(rstudio.markdownToHTML =
function(inputFile, outputFile) {
system(paste("pandoc", shQuote(inputFile), "-s --webtex -o", shQuote(outputFile)))
}
)
}
Unfortunately, when I open the RStudio app neither of them appear to be working. The aim of what I'm trying to do is to make the "Knit HTML" button render the Markdown file, which has inline LaTeX, process through Pandoc using webtex as the LaTeX renderer.
Does anyone know how I check whether my .Rprofile files are loading at startup?
Thanks for any help!
POST ANSWER EDIT (after Josh's answer):
For clarity, my working project's .Rprofile file (which works) now reads as such:
options(rstudio.markdownHTML =
function(inputFile, outputFile) {
system(paste("pandoc", shQuote(inputFie), "-s --webtex -o", shQuote(outputFile)))
}
)
\\ you will need to end with a blank carriage return underneath

The R docs should help to see how to deal with .Rprofiles. Execute the following at the console:
> ?Startup
The relevant portion of this indicates that you need to put your project .Rprofile in the initial working directory that will be loaded when starting the project. Thus if your project is ~/foo/foobar.Rproj, then you should have your profile be ~/foo/.Rprofile and make sure that when starting up, the initial working directory is ~/foo/. You can see this in the title bar at the top of the console pane in RStudio.
Also to confirm that the correct .Rprofile is actually being loaded, I would personally put in a test to see which (if any) profile is being picked up. For example, include:
print("This is the Rprofile inside the foo project!")
Here is another example about getting this to work:
http://support.rstudio.org/help/discussions/suggestions/1095-different-rprofile-for-a-project#comment_15690293
Finally, if the correct .Rprofile is being loaded inside the project, then there must be something wrong with your code. Looks like you got this from our docs though, so if you get the profile loaded, and continue to have problems, please let us know. You can post a new discussion on our support thread.
Josh
Product Manager - RStudio

Related

R extension on VS Code - keyboard shortcut NOT working

I have installed R extension and radian to use R from VS code.
I wanted to run selected line(s) as I do in Rstudio.
Even though it appears to be set among "Keyboard Shortcuts" the shortcut cmd+enter (see pic) doesn't seem to work. Anyone can think of why?
I figured it out!
First a clarification: the issue was only affecting code in *.rmd|*.Rmd files, while normal *.R script were doing OK.
As for the *.rmd files, following the instructions here I added this in my settings.json file:
{
"files.associations": {
"*.Rmd": "rmd"
}
}
Now my shortcut cmd+enter works like a breeze ✅
PS: there may be issues also with conflicting keyboard shortcuts. In fact I deleted some that I have no interest in, but that did not solve it.

qmake's write_file() and system() doesn't want to make a file

I've got a strange behavior of qmake while trying to write smth to another file. I read all possible manuals and searched out the internet but found nothing similiar. Closer to the simplest possible code:
!system(echo 1 > d:\1.txt) {
warning(Cant create a file)
}
It doesn't create a file, and it doesn't show a warning, that means that operation succeded. Another example:
var = test string
file = $$absolute_path(d:\1.txt)
message(Variable: $$var and filename: $$file)
!write_file($$pathBat, pathtowrite) {
warning(Cant create a file)
}
This block produces output:
Project MESSAGE: Variable: test string and filename: d:/1.txt
And nothing is said about the fact the file has not been created.
I've already checked the rights to write to the directory: everything seems fine.
Can anybody help me with this?
UPD:
I've found something else: message($$system(echo 1 > 1.txt)) works fine. And this is what makes me cry, because I really don't understand what is going on.
Huh! I found the solution and it may sounds like buy yourself some brain. I thought, that qmake is launched every time the project file is changed (output of message commands proved my thoughts), but it's not really the way things happen in Qt.
I don't know how exactly, but it parses the .pro file, does only some necessary operations, and as I can see system() (which is going to change some file), write_file() commands doesn't seem to be invoked.
The SOLUTION is so much simple: natively launch qmake using the Build - Launch qmake.

Issue with .Rprofile file when trying to upload to RPubs

From what I can gather there is a well documented issue with uploading Rpubs to RStudio. The solution is to create a .Rprofile and with an additional line:
options(rpubs.upload.method = "internal")
and then put the .Rprofile file in your working directory, and restart the program. My issue is that when I attempt this and start up RStudio I am presented with the error:
Error in assign(".popath", popath, .BaseNamespaceEnv) :
cannot change value of locked binding for '.popath'
Can anyone suggest what I may be doing wrong? What have I missed?
The solution is provided by a careful rereading of http://rstudio-pubs-static.s3.amazonaws.com/25030_8e9c9ffc3b3c423d9381d81543423502.html
"Put in options(rpubs.upload.method = “internal”) and no other text at all". Meaning that this line of code is the only code present in the .Rprofile file.
Previously I had been adding the line to a copy of the rest of the Rprofile text. The unnecessary code was the culprit.

Make R project Automatically open Specific Scripts

I am working in team, we mainly use R, I am quite used to use R project in Rstudio, which I like because when I open them I have all my scripts and everything at the right place. However when another member of the team opens one of my project it loads the values and data but does not open the R script (one can see that by physically clicking on the project through the windows explorer rather than using the menu at the top right in R). I guess something can be done in the .Rprofile but I did not find any command to open physically a script, I tried
file.edit("./Main.R")
but it did not open anything. It just got me the message :
Error: could not find function "file.edit"
As always,
Thanks for your help !
**EDIT
I tried to use
file.show
file.edit
shell.exec(file.path(getwd()), "Main.R"))
in the .Rprofile. Nothing worked.
Romain
You can use the following code in the .Rprofile file.
setHook("rstudio.sessionInit", function(newSession) {
if (newSession)
rstudioapi::navigateToFile('<file name>', line = -1L, column = -1L)
}, action = "append")
The rstudioapi library has the function navigateToFile to open a file in Rstudio. The problem is that the code in the .Rprofile runs before Rstudio initialization. To deal with this problem you can use the setHook function (from base package) to make the code execute after the Rstudio initialization.
file.edit requires the utils package
library(utils)
file.edit("Master.R")
However, if it opens in Notepad rather than RStudio you have the same problem as me. I've tried editing the editor= in all possible places: .RProfile, RProfile, RProfile.sites, with and without .First() function statements and calls. However, RStudio does not load the .R file in RStudio if told to. It may be linked to the .RData file being loaded after .RProfile. Bug? Or at least a feature RStudio should incorporate in their RProject file specification.

get filename and path of `source`d file

How can a sourced or Sweaved file find out its own path?
Background:
I work a lot with .R scripts or .Rnw files.
My projects are organized in a directory structure, but the path of the project's base directory frequently varies between different computers (e.g. because I just do parts of data analysis for someone else, and their directory structure is different from mine: I have projects base directories ~/Projects/StudentName/ or ~/Projects/Studentname/Projectname and most students who have just their one Project usually have it under ~/Measurements/ or ~/DataAnalysis/ or something the like - which wouldn't work for me).
So a line like
setwd (my.own.path ())
would be incredibly useful as it would allow to ensure the working directory is the base path of the project regardless of where that project actually is. Without the need that the user must think of setting the working directory.
Let me clarify: I look for a solution that works with pressing the editor's/IDE's source or Sweave Keyboard shortcut of the unthinking user.
Just FYI, knitr will setwd() to the dir of the input file when (and only when) evaluating the code chunks, i.e. if you call knit('path/to/input.Rnw'), the working dir will be temporarily switched to path/to/. If you want to know the input dir in code chunks, currently you can call an unexported function knitr:::input_dir() (I may export it in the future).
Starting from gsk3's Seb's suggestions, here's an idea:
the combination of username (login) and IP or name of the computer could be used to select the right directory.
That leads to something like:
setwd (switch (paste (Sys.info () [c ("user", "nodename")], collapse="."),
user.laptop = "~/Messungen",
user2.server = "~/Projekte/Projekt/",
))
So there is an automatic solution, that
works with source
works with Sweave
even works for interactive sessions where the commands are sent line by line
the combination of user and nodename of course needs to be specific
the paths need to be edited by hand, though.
Improvements welcome!
Update:
Gabor Grothendieck answered the following to a related question on r-help today:
this.dir <- dirname(parent.frame(2)$ofile)
setwd(this.dir)
which will work for source.
Another update: I now do most of the data analysis work in RStudio. RStudio's projects basically solve the problem: RStudio changes the working directory to the project root directory every time I switch between projects.
I can therefore put the project directory as far down my directory tree as I want (and the students can also put their copy wherever they want) and sync the data files and scripts/.Rnws via version control (We use a private git server). The RStudio project files are kept out of the version control, i.e. .gitignore contains .Rproj.user.
Obviously, within the project, the directory structure needs to be synchronized.
You can use sys.calls() to get the command used to source the file. Then you need a bit of trickery using regular expressions to get the pathname, bearing in mind that source("something/filename") could have used either the absolute or relative path. Here's a first attempt at putting all the pieces together: try inserting the following lines at the top of a source file.
whereFrom=sys.calls()[[1]]
# This should be an expression that looks something like
# source("pathname/myfilename.R")
whereFrom=as.character(whereFrom[2]) # get the pathname/filename
whereFrom=paste(getwd(),whereFrom,sep="/") # prefix it with the current working directory
pathnameIndex=gregexpr(".*/",whereFrom) # we want the string up to the final '/'
pathnameLength=attr(pathnameIndex[[1]],"match.length")
whereFrom=substr(whereFrom,1,pathnameLength-1)
print(whereFrom) # or "setwd(whereFrom)" to set the working directory
It's not very robust—for instance, it will fail on windows with source("pathname\\filename"), and I haven't tested what happens if you have one file sourcing another file—but you might be able to build a solution on top of this.
I have no direct solution how to obtain the directory of the file itself but if you have a limited range of directories and directory structures you can probably use
if(file.exists("c:/somedir")==TRUE){setwd("c:/somedir")}
You could check out the pattern of the directory in question and then set the dir. Does this help you?
An additional problem is that the working directory is a global variable, which can be changed by any script, so if your script calls another script, it will have to set the wd back. In RStudio I use Session -> Set Working Directory -> To Source File Location (I know, it's not ideal), and then my script does
wd = getwd ()
...
source ("mySubDir/myOtherScript.R", chdir=TRUE); setwd (wd)
...
source ("anotherSubDir/anotherScript.R", chdir=TRUE); setwd (wd)
In this way one can maintain a stack of working directories. I would love to see this implemented in the language itself.
This answer works for source and also inside nvim-R - I have no idea if it works with knitr and similar things. Any feedback appreciated.
If you have multiple scripts source-ing each other, it is important to get the correct one. That is, the largest i for which sys.frame(i)$ofile exists.
get.full.path.to.this.sourced.script = function() {
for(i in sys.nframe():1) { # Go through all the call frames,
# in *reverse* order.
x = sys.frame(i)$ofile
if(!is.null(x)) # if $ofile exists,
return(normalizePath(x)) # then return the full absolute path
}
}

Resources