Why does R source() sometimes work and sometimes gives an error - r

I have the API credentials in one separate R script to keep it out of Git. I want to run this script in the beginning of the scripts that actually interact with the different servers. I have successfully used the same strategy for all my global functions.
setwd("G:/script")
source("API_credentials.R") # gives always an error
# > source("API_credentials.R")
# Error: '\s' is an unrecognized escape in character string starting ""g:\s"
source("ProVeg_functions.R") # runs fine
Problem:
Why does the first source() not work, while the second one does? The error message does not make any sense to me.
Solutions tried:
I have tried different escape chars \.
I have tried writing full path & file names.
I have tried putting the file name in as a variable, which gets its
content from a dir() search, to make sure that the file exists and
the name is correctly written.
Order of source() does not change situation.
Isolating the piece of code with error, and restarting R.
upgraded all my packages and R to version 4.0.2.
The API_credentials.r script works fine when run on its own. the Sys.setenv() works fine and I can read the API keys with Sys.getenv().
I am not sure if it is related to my problem, but if I do usethis::edit_r_environ() I can not see my API keys.
Setup
Windows 10, R-Studio 1.3.1093, R version 4.0.2 (2020-06-22)

I mistakenly assumed that the error message was related to the script calling the API_credentials.R, but it actually was an error message indicating an error in the API_credentials.R script. Fixed a typo and all is good.

Related

RMarkdown: how to get english error messages on a localised system

I am writing a vignette in RMarkdown and I want to point out a programming mistake.
listofnumbers <- as.list(1:4)
listofnumbers[2] + listofnumbers[3]
This code snippet produces an error:
Error in listofnumbers[2] + listofnumbers[3] : non-numeric argument
to binary operator
However, I am working on a system localised to German. The error message I get is in German:
Error in listofnumbers[2] + listofnumbers[3]: nicht-numerisches Argument für binären Operator
If anyone renders the vignette themselves that may be good. But to pre-render it with the package I would need the English message.
Also, I do not want to change my system settings permanently to English.
I investigated using an output hook. But I do not know how to translate the German message to English.
I am working on Windows 10.
If the environment variable LANGUAGE is set to en, error messages will be displayed in English. This needs to be in place at the time R starts.
If you are using RStudio, then it starts a new copy of R to process vignettes when you click on Knit, so you can do this in the current session using
Sys.setenv(LANGUAGE="en")
That should also work if the vignette is processed when you build the package as long as you start a new session to do the build. By default devtools::build() and related functions do that.
If you are running RMarkdown within the current session (e.g. by calling rmarkdown::render()) that won't work, because it happens too late. In that case you can use OS features to set the environment variable, or set it in the .Renviron file in your home directory as
LANGUAGE=en
Since you say you are on Windows, you have to do this carefully: Windows doesn't like filenames like .Renviron, and may try to change it to something else.
This method should work if you use R CMD build to build your packages outside of RStudio.

Accent in my user folder generates an error in execution of read_csv()

I'm having trouble executing the routine read_csv(), I'm pretty sure it is because my user folder has an accent and that gives an 'file not found' error:
> statics <-read_csv("statics.csv")
Error: Timezone database not found at
"C:/Users/Administracién/Documents/R/win-library/4.1/tzdb/tzdata"
In the route there is a 'é' that I assume is causing the problem. I can't change the name of my user folder without making many of the programs of my system crash, so I don't know how to solve this... Any ideas how to solve it?
I tried editing the environmental variables, setting:
R_LIBS_USER C:/Users/Administración/Documents/R/win-library/4.1
And with this, as before, I can load libraries as tidyverse, installed there, without problems, but when I use that read_csv() routine crashes because it searches it in the folder changing the accent for those strange character.
The two symbols you are using in your pathway aren't recognized by R.
R can recognize them with the unicode symbol.
à is "\u0200" in R code
© is "\u00a9" in R code
Does this work with your pathway?
setwd(paste("C:/Users/Administraci","\u0200","\u00a9","n/Documents/R/win-library/4.1/tzdb/tzdata",sep=""))
read_csv("statics.csv")

R: "Error calling capture_console_output: 87" when using terminalExecute()

I am trying to run an executable called swat_edit.exe in R. It works perfectly when I run it directly in the command prompt, and also when I run it directly in the Terminal tab in R. However, when I try to write a function in R to run the executable, I get an error (I get a number of different errors...).
I have tried to use different methods of running the file:
1: I used system("swat_edit"), which returns the following error:
Unhandled Exception: System.IO.IOException: The handle is invalid.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.Console.set_CursorVisible(Boolean value)
at SWEdit.Program.Run(String[] args)
at SWEdit.Program.Main(String[] args)
[1] 17234
2: I used shell("swat_edit"), which returns the exact same error as (1).
3: I used shell.exec("swat_edit"). This works, but it opens the executable in a new window, which then runs for a few seconds and closes (as intended). I need the program to run in the R terminal window so it can run many iterations in the background without disrupting other things. This is not a viable option.
4: I tried using terminalSend(ID,"swat_edit") (from the rstudioapi package). This works in that it sends the command to the terminal window in R. When I move there and hit enter it executes perfectly, running in the terminal window like I want it to. However, I need to run many iterations so this is not viable either. I tried using KeyboardSimulator to go to the Terminal tab and hitting enter (which worked), but this also does not let me use the PC for other purposes while running my code.
5: I tried using terminalExecute("swat_edit"), which returns the following error code:
Error calling capture_console_output: 87
[Process completed]
[Exit code: -532462766]
6: I tried making a python file that runs swat_edit.exe, and then running that file in R. The python file works when I run it by itself, from the command prompt, or from the terminal in R. It does not, however, work when I try to run it in the R terminal using terminalExecute (same error as in (5)).
NOTE: I have another executable called swat.exe (entirely different program) that works with all of the above-mentioned methods.
So in summary: swat_edit.exe runs perfectly in command prompt and R terminal, but does not work when I try to run it using R code (either system(), shell(), or terminalExecute().
I can't figure out the difference between terminalExecute() and typing the string into terminal and hitting enter, but apparently there is something happening in between...
It will be tedious to reproduce this since it uses external programs, but if anyone has any idea about the error messages or how I can copy a string and run it in the terminal without any interference, that would be greatly appreciated.
EDIT: I found a method that solves my problem. I created a .bat file that runs swat_edit minimized. I was able to run this .bat file with the shell function (or any of the other commands I mentioned) in R. This doesn't answer why I was having the issues I described, and it doesn't let me run swat_edit in the R terminal, but it's good enough for me.
The .bat file was simply the following:
"START /MIN /WAIT C:\~\SWAT_Edit.exe"

R starts up with error message

I am asking this question out of curiosity. I have noticed that whenever I boot R, the instance starts up with this error message
As you can see, R boots with the error message "object 'a' not found" Is there any reason for this?
R reads and executes several files at startup, most prominently the ~/.Rprofile file (That is, the file .Rprofile in your home directory). Check these files to see if they contain anything weird.
You can quickly check whether .Rprofile is the culprit by running R with the --vanilla command line argument: this argument prevents the user profile to be read, thus the error should vanish.

tryCatch error: the action can´t be completed because the folder is open in RStudio R session

When I download files (Windows 7) using
tryCatch(download.file(paste0(url_bv,arq), paste0(dir_bv,arq))
,error=function(cond) message(paste('erro:',arq,'não encontrado'))
,warning=function(cond) message(paste('warning:',arq,'não encontrado')))
I can´t delete files, getting the msg in the question title.
If I just do
download.file(paste0(url_bv,arq), paste0(dir_bv,arq))
there is no problem.
How can I release the folder/file in R?
I think this is likely a bug in R (windows version). I can faithfully reproduce it in R-3.2.5 (win10_64). I suggest you file a bug report (read R FAQ 9.2 for clear direction).
I tried it with several variations:
different url schemes ("http://" and "https://")
different download.file(..., method=...) options ("wininet", "internal", and "auto" all behaved in this manner; "libcurl" did not, but it merely downloaded the 404.html without telling me there was a problem)
triggers whenever warning=... or condition=... clauses are given to tryCatch and something weird happens in expr
does not trigger with error=... or finally=... arguments
32bit and 64bit variants
not in RStudio
as R --vanilla
All attempted on ubuntu-14.04 (R-3.2.3-64bit) as well, it would not trigger.

Resources