= 12 myvar
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:
- a simple variable
- a data frame
- a spatial data frame (sf)
1 - a simple variable
{r}
Here we have a variable myvar which is 12.
The ojs_define instruction simply makes this variable accessible in Observable
ojs_define(myvar)
{ojs}
myvar
1 - a dataframe
{r}
In this second case, we import a csv file.
<- read.csv("data/stat.csv") data
As before, we use ojs_define to make this variable accessible in Observable. We rename this variable to newdata.
ojs_define(newdata = data)
{ojs}
Warning, if we visualize this data table in Observable directly, we realize that it does not really have the expected form.
newdata
Thankfully, the transpose instruction allows you to convert the table to the correct format.
= transpose(newdata)
data data
.table(data) Inputs
3 - a spatial data frame (sf)
{r}
In this third case, we import a geopakage thanks to the library sf, containing the countries of the world.
library("sf")
<- st_read("data/countries.gpkg", quiet = T)
countries plot(st_geometry(countries))
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.
library("geojsonsf")
ojs_define(geo = sf_geojson(countries))
{ojs}
Note that with ojs_define, we have passed the variable geo as a string and not actually as an object.
.substr(1, 300) geo
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.
= JSON.parse(geo)
countries countries
Now everything is ok to make a map in Observable. See more here.
= import('https://cdn.skypack.dev/bertin@0.9.12')
bertin .draw({
bertinlayers: [
{geojson: countries,
tooltip:["$ISO3","$NAMEen"]
}
] })
4 - Another solution
Another way to pass variables and data from R to Observable is to save and then import data.
{r}
As before, we import a geopackage in R with sf.
<- st_read("data/countries.gpkg", quiet = T) countries
Then we convert it to geojson and save it in the data directory.
write(sf_geojson(countries), "data/world.geojson")
{ojs}
In observable, we just have to import this data file in geojson (or other) format.
= FileAttachment("data/world.geojson").json() world
Let’s take a look at it!
.quickdraw(world) bertin