Opening two Rstudio sessions while one is sinking - r

In Rstudio I have one script which is running and using sink() to save the outputs to a text file. However, when I open up a second R studio session, while the first session is still running, it seems like I am unable to print anything to the console. How do you print to the console in Rstudio while another session is using sink?
For example open up Rstudio and start by setting workspace to source file, with this as your source file
#set up sinking
logFile = file("logMod.txt")
sink(file=logFile)
N=10000;
N.c=10000;
#run program
for (i in 1:N){
for (j in 1:N.c){
if( i*j %% 10000==0 ) print(i*j)
}
}
sink()
then open up another Rstudio session and try to print to console. I can't do it. I can open the standard R gui and print to console but not Rstudio. This is all done on a windows machine.

Related

R: "internet routines cannot be loaded" when starting from RStudio

I am running Red Hat Enterprise Linux (RHEL) 8.5 with Linux kernel 4.18 and Gnome 3.32.2. In this system, I've got R 4.1.2 compiled with the tool asdf with shared libraries enabled. On top of that, I installed RStudio 2021.09.01-372 from an RPM from the official RStudio website.
When I start Rstudio, the first line of output after the usual R startup is an error:
Error in tools::startDynamicHelp() : internet routines cannot be loaded
I am unable to figure out what's causing this error, and with it I can't run things like refresh CRAN or update packages. But if I start a pure R session from the terminal (instead of Rstudio) this error does not occur.
Some things I tried:
Install the krb5 and libssh2 packages on my host system: Didn't help.
Starting a "pure" R session (both with and without the --vanilla argument) from the Terminal tab within Rstudio also gives this error. If I try to run update.packages() from this session, it pops up a window to select a CRAN mirror then fails with the following:
Warning: failed to download mirrors file (internet routines cannot be loaded); using local file '/home/[my username]/.asdf/installs/R/4.1.2/lib64/R/doc/CRAN_mirrors.csv'
Warning: unable to access index for repository https://cloud.r-project.org/src/contrib:
internet routines cannot be loaded
Warning message:
In download.file(url, destfile = f, quiet = TRUE) :
unable to load shared object '/home/penyuan/.asdf/installs/R/4.1.2/lib64/R/modules//internet.so':
/lib64/libssh.so.4: undefined symbol: EVP_KDF_ctrl, version OPENSSL_1_1_1b
But like I said, the strange thing is if I start an R session outside of Rstudio, these errors don't happen.
Within RStudio, the only workaround I can find is to run this command upon startup (suggested in this thread):
options(download.file.method="wget")
Once this is done, everything else seems to work, such as package updates.
However, I don't want to manually do this every time I start RStudio. So I tried to put it into ~/.Rprofile including a test print() as follows:
print("This is `~/.Rprofile`")
options(download.file.method="wget")
When I open RStudio, I can see the output from the print() call, but the options() command is not run because the original error shows up again. I still have to manually enter options(download.file.method="wget") every time.
I also tried to fold everything into a .First function in ~/.Rprofile as follows:
.First <- function() {
options(download.file.method="wget")
print("This is the `.First` function in `~/.Rprofile`")
}
Unfortunately, same result as before: print()'s output is seen, but options() is not run.
I also made sure that my ~/.Rprofile includes a trailing newline as discussed here. But this didn't help.
The above are the steps I've tried so far.
Why does this error only occur when running RStudio or a terminal within Rstudio? Why doesn't it happen if I start R from a terminal outside of Rstudio?
Is there a way to solve the problem so that the error doesn't happen in the first place? If it can't be solved, how do I set up my ~/.Rprofile so that options(download.file.method="wget") will be run?
Thank you.

How to release R's prompt when using 'system'?

I am writing an R code on a Linux system using RStudio. At some point in the code, I need to use a system call to a command that will download a few thousand of files from the lines of a text file:
down.command <- paste0("parallel --gnu -a links.txt wget")
system(down.command)
However, this command takes a little while to run (a couple of hours), and the R prompt stays locked while the command runs. I would like to keep using R while the command runs on the background.
I tried to use nohup like this:
down.command <- paste0("nohup parallel --gnu -a links.txt wget > ~/down.log 2>&1")
system(down.command)
but the R prompt still gets "locked" waiting for the end of the command.
Is there any way to circumvent this? Is there a way to submit system commands from R and keep them running on the background?
Using ‘processx’, here’s how to create a new process that redirects both stdout and stderr to the same file:
args = c('--gnu', '-a', 'links.txt', 'wget')
p = processx::process$new('parallel', args, stdout = '~/down.log', stderr = '2>&1')
This launches the process and resumes the execution of the R script. You can then interact with the running process via the p name. Notably you can signal to it, you can query its status (e.g. is_alive()), and you can synchronously wait for its completion (optionally with a timeout after which to kill it):
p$wait()
result = p$get_exit_status()
Based on the comment by #KonradRudolph, I became aware of the processx R package that very smartly deals with system process submissions from within R.
All I had to do was:
library(processx)
down.command <- c("parallel","--gnu", "-a", "links.txt", "wget", ">", "~/down.log", "2>&1")
processx::process$new("nohup", down.comm, cleanup=FALSE)
As simple as that, and very effective.

How to wait for user input in R-script ran from Windows CMD

I'm new to R and I'm stuck in a very simple task.
I want to run an R script from console, but I want the script to be able to read user inputs.
This is how I'm reading from the script:
library = readLines(n = 1L)
if(library == "1")
{
library = "GUDHI"
}
And this is how I'm running my script from R-Portable with a .bat:
#echo on
cd..
cd..
cd..
cd..
cd..
PATH C:\Users\MyUser\Desktop\App\RFolder\R-Portable\App\R-Portable\bin;%path%
cd C:\Users\MyUser\Desktop\App\RFolder
Rscript Phom.R 1
pause
When I run this .bat it throws an error (Argument is of length zero):
As if the console didn't wait for user input.
The problem is not the .bat code. If I remove the readLines functions from my script and hardcode the input, it works perfectly. I also tried the readline function with no success.
Thanks.
Solution for Interactive R script from Windows CMD:
cat("Prompt Message: ")
library = readLines(con = "stdin", 1)
I'm not sure if the prompt MUST end with ": ", but I had trouble when I removed that piece of string.
This worked for me, I hope this helps somebody.

AutoIt and RSelenium to navigate Save As dialogue (Firefox)

I have been trying now for days (if not weeks...) to get the code below to work. What I am trying to achieve is that an R script runs daily (via batch script and Windows Task Scheduler on Windows Server 2008 64bit).
That R script shall navigate to certain websites, log in and invoke the Save As dialogue to save complete pages to a specific path.
If I run my script on my machine (Win 8 - 64bit) within RStudio it works like a charme - remotely and via Rscript.exe it does not.
The problem appears to be with the SaveAs.au3 script - when I call it via RStudio or from file explorer it works perfectly. The same R Script executed within a batch file with:
"C:\Program Files\R\R-3.2.3\bin\x64\Rscript.exe" "C:\JN\abc.R"
works up until the system() command as well and crahses then without providing any error or warning.
Maybe there is someone who had a similar problem and can help? Thanks!
The 3 AutoIt scripts are the following:
SaveAs.au3 / exe
ControlFocus("[CLASS:MozillaWindowClass]", "", "")
ControlSend("[CLASS:MozillaWindowClass]", "", "", "^s")
EditName.au3 will be variably written from within R and then called
KeyEnter.aut3
ControlFocus("Save as", "", "")
ControlClick("Save as","","[CLASS:Button; INSTANCE:1]")
The R script looks as follows:
# compl is a vector of n href
if(length(compl) != 0) {
foreach(i=1:length(compl)) %do% {
server_check() # checks whether selenium driver is still active and firefox window is open
remDr$navigate(compl[i])
Sys.sleep(10)
login_check() # checks whether login is still active
Sys.sleep(5)
print(paste("attempt to save:",compl[i]))
system('C:\\JN\\SaveAs.exe') # does not matter whether .exe or .au3
Sys.sleep(3)
system("cmd", input = c('echo ControlSetText("Save as", "", "[CLASS:Edit; INSTANCE:1]", "") > C:\\JN\\EditName.au3',
paste0('echo ControlSend("Save as", "", "[CLASS:Edit; INSTANCE:1]", "',
gsub("/","_",gsub(website_url,"", compl[i])), ".htm",
'") >> C:\\JN\\EditName.au3')))
Sys.sleep(3)
system('C:\\"Program Files (x86)"\\AutoIt3\\AutoIt3.exe C:\\JN\\EditName.au3')
Sys.sleep(8)
system('C:\\"Program Files (x86)"\\AutoIt3\\AutoIt3.exe C:\\JN\\KeyEnter.au3')
Sys.sleep(30)
}
}
print("Complete save end")
The problem was related to Windows Server 2008 R2 - if you disconnect from the remote session the server will initiate a screen server (or alike) making the AutoIt script unable to interact with the GUI (as there is non...)
There are options within Windows Server to prevent the server from disabling the GUI, but my script was still not stable enough to run on its own for months...

Starting Rserve in debug mode and printing variables from Tableau to R

I can't start Rserve in debug mode.
I wrote these commands in R:
library(Rserve)
Rserve(debug=T, args="RS-enable-control", quote=T, port = 6311)
library(RSclient)
c=RSconnect(host = "localhost", port = 6311)
RSeval(c, "xx<-12")
RSeval(c, "2+6")
RSeval(c, "xx")
RSclose(c)
install.packages("fpc")
I placed the Rserve_d.exe in the same directory where the R.dll file is located. But when I launch it and I launch Tableau with the Rserve connection I can't see anything in the debug console, just these few lines.
Rserve 1.7-3 () (C)Copyright 2002-2013 Simon Urbanek
$Id$
Loading config file Rserv.cfg
Failed to find config file Rserv.cfg
Rserve: Ok, ready to answer queries.
-create_server(port = 6311, socket = <NULL>, mode = 0, flags = 0x4000)
INFO: adding server 000000000030AEE0 (total 1 servers)
I tried another solution by the command Rserve(TRUE) in R, but I can't see the transactions between R and Tableau neither in the Rstudio console.
I wanted then to print the output of the variable in R from the R-script function, by print(.arg1). But nothing appears in the R console
but when I run print in the R console it works fine.
According to this article*, RServe should be run with the following command to enable debugging:
R CMD Rserve_d
An alternative is to use the ‘write.csv’ command within the calculated field that calls an R script, as suggested by this FAQ document from Tableau
Starting Rserve_d.exe from command line works. Most likely you have multiple instances of Rserve running and Tableau is sending requests to one that is not Rserve_d running in the command line.
Did you try killing all Rserve processes and then starting Rserve_d from command line?
If you don't want to run from the command line you can try starting Rserve in process from RStudio by typing run.Rserve() then using print() statements in your Tableau calculated fields for things you want to print.
In the R bin directory, you have two executables Rserve for normal execution and Rserve.dbg for debug execution. Use
R CMD Rserve.dbg
My OS is CENTOS7 and I am using the R installation from anaconda. If your RServe debug executable has a different name you should be using that.

Resources