Adding IDE features to text editor: Communicate with R session in the background or invisible commands-e.g. get loaded packages from other application

StackOverflow https://stackoverflow.com/questions/23538930

  •  17-07-2023
  •  | 
  •  

Question

is it possible to communicate with a R session in the background or execute an invisible command on the Mac? For example, I would like to get the packages loaded in a particular R session. Or I would like to get the variable names in df (a data.frame).

This would be very useful to add IDE like features to a text editor such as sublime text. For example, when I type df$, ST or some other editor could open an auto-complete popup with the variables in df. A two-way pipe would be optimal of course. An alternative would be to execute invisible commands in the current session that the user can't see. These commands could write the output to a text file.

Is that somehow possible either using the Mac GUI or an R session in the terminal?

Was it helpful?

Solution

This is possible using the svSocket package. The package "Implements a simple socket server allowing to connect GUI clients to R" and is not blocking R. Rserve provides similar capacities and also has libraries for other languages but blocks the R session.

In the main R session: require('svSocket') startSocketServer(port=8888) df = data.frame(var1=1:100,var2=4)

Now you can communicate with the main R session from other R session: require('svSocket') con = socketConnection(port=8888) evalServer(con, ls()) evalServer(con, names(df)) Which lists all the objects in the main R session and returns the names of the data.frame df.

There are different methods to use this approach from Python or other languages. One possibility is the subprocess module args = ['RScript', '--vanilla'] args.extend(['-e', 'require("svSocket")']) args.extend(['-e', 'con = socketConnection(port=8888)']) args.extend(['-e', 'evalServer(con, ls())']) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() The disadvantage of this approach is that it starts a new R session every time you run this code in Python, which is not very fast. Rserve has a python client and something similar might be possible for svSocket (not sure though). The speed is a limitation if you need immediate access to information about objects in the main R workspace. In that you might want to cache information from the main R session in certain intervals and use this cache for whatever you want to do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top