Quarto: ojs_define & transpose

In this document, we show how it is possible to pass a variable from R to Observable. We deal with 3 cases:

1 - a simple variable


Here we have a variable myvar which is 12.

myvar = 12

The ojs_define instruction simply makes this variable accessible in Observable




1 - a dataframe


In this second case, we import a csv file.

data <- read.csv("data/stat.csv")

As before, we use ojs_define to make this variable accessible in Observable. We rename this variable to newdata.

ojs_define(newdata = data)


Warning, if we visualize this data table in Observable directly, we realize that it does not really have the expected form.


Thankfully, the transpose instruction allows you to convert the table to the correct format.

data = transpose(newdata)

3 - a spatial data frame (sf)


In this third case, we import a geopakage thanks to the library sf, containing the countries of the world.

countries <- st_read("data/countries.gpkg", quiet = T)

To create a map in Observable, we first need to convert this data set to geojson format. To do this, we use the geojsonsf library. Then, the ojs_define() instruction allows to define this variable within ojs cells.

ojs_define(geo = sf_geojson(countries))


Note that with ojs_define, we have passed the variable geo as a string and not actually as an object.

geo.substr(1, 300)

The first thing to do here is to transform our string into a real object. To do this, we use the javascript statement JSON.parse.

countries = JSON.parse(geo) 

Now everything is ok to make a map in Observable. See more here.

bertin = import('https://cdn.skypack.dev/bertin@0.9.12')
  layers: [
      geojson: countries,

4 - Another solution

Another way to pass variables and data from R to Observable is to save and then import data.


As before, we import a geopackage in R with sf.

countries <- st_read("data/countries.gpkg", quiet = T)

Then we convert it to geojson and save it in the data directory.

write(sf_geojson(countries), "data/world.geojson")


In observable, we just have to import this data file in geojson (or other) format.

world = FileAttachment("data/world.geojson").json()

Let’s take a look at it!


That’s all folks!