Edit and run R code inside Logseq itself

  • The theoretical background and discussion is here.
  • This is a natural continuation of the work done in Edit and run javascript code inside Logseq itself
    • The implementation there supports multiple languages, so it is not repeated here.
    • This is opened as a separate thread, in order to hold the R-specific material and discussion.

Current Features:

  • It loads WebR the first time that is needed per Logseq’s restart.
    • It looks for file webr-worker.js inside Logseq’s installation (where file electron.js is).
      • Can get the contents from the internet, by creating the file yourself and putting inside a single line:
        • importScripts('https://webr.r-wasm.org/latest/webr-worker.js');
  • It doesn’t load other packages.
    • Instructions can be found online (e.g. here).
  • All the integrated parts are provided from third parties.
    • Their quality is not perfect.
    • Use at own risk.
      • Expect failures in various cases.
      • Thoroughly test all code before using it in production.
      • There is a known issue of a console message “Service worker request failed - resending request” with a one-minute interval.
  • More info and abilities found in Edit and run javascript code inside Logseq itself, so not repeated here.

Check for the following messages during first run:
image

image

Simple example

image

Example of mixing and running javascript and R in the same page

Use the following markdown in a page:

- Code
	- {{runpage}}
	-
	  ```javascript
	  logseq.can_run = "java?";
	  
	  const rEnv = logseq.modules.R.Webr.objs.globalEnv;
	  return rEnv.bind("can_run", logseq.can_run);
	  ```
	-
	  ```r
	  rfun <- function(str){
	      c <- c(substring(can_run, 1, nchar(can_run) - 1), str, " & r-")
	      paste(c, collapse="")
	  }
	  ```
	-
	  ```javascript
	  const Webr = logseq.modules.R.Webr;
	  const rfun = await Webr.evalR("rfun");
	  const res = await rfun("script");
	  return Webr.objs.globalEnv.bind("can_run", res.values[0]);
	  ```
	-
	  ```r
	  c <- c(can_run, "language")
	  can_run = paste(c, collapse="")
	  get_can_run <- function(){ can_run }
	  ```
	-
	  ```javascript
	  const get_can_run = await logseq.modules.R.Webr.evalR("get_can_run");
	  const res = await get_can_run();
	  alert("Logseq can edit & run: clojure & " + res.values[0] + " & python");
	  ```

Should look like this:

Press the button for javascript and R to collaborate back and forth, joining forces to produce a fact.