ObservableJS in Quarto

Integrating OJS and R in Quarto

Author

Roy Francis

Published

06-Sep-2024

Passing data

Convert R data.frame to OJS object. This is the only code chunk that is R. All other chunks are ojs.

Code
R code
irism <- iris
colnames(irism) <- gsub("[.]","_",tolower(colnames(irism)))
ojs_define(ojsd = irism)

Transpose JS object.

Code
ojsdata = transpose(ojsd)

Raw JSON object.

Code
ojsdata

Table

Display as table.

Code
viewof raw_table = Inputs.table(ojsdata)

Computing a new variable using an arrow function. ... keeps all old variables and the new variable ratio is added.

Code
ojsdatamod = ojsdata.map(d => ({...d, ratio: d.sepal_width / d.petal_width}))
Code
viewof mod_table = Inputs.table(ojsdatamod)

Checkbox filtering

Define checkbox input.

Code
viewof grp = Inputs.select(["setosa", "versicolor", "virginica"], {value: ["setosa"], multiple: false, label: "Species"})

Filter data based on checkbox inputs.

Code
ojsdata_filtered = ojsdata.filter(d => d.species.includes(grp))

Display filtered data as table.

Code
viewof filtered_table = Inputs.table(ojsdata_filtered)

Scatterplot

Display a scatterplot. X and Y axes are defined by select inputs.

Code
viewof x = Inputs.select(Object.keys(ojsdata[0]), {value: "sepal_length", multiple: false, label: "X axis"})
Code
viewof y = Inputs.select(Object.keys(ojsdata[0]), {value: "sepal_width", multiple: false, label: "Y axis"})
Code
Plot.plot({
  marks: [
    Plot.dot(ojsdata, {
      x: x,
      y: y,
      fill: "species",
      title: (d) =>
        `${d.species} \n Petal length: ${d.petal_length} \n Sepal length: ${d.sepal_length}`
    })
  ],
  grid: true
})

Arquero

Data wrangling using Arquero.

Import dependencies and convert data to Arquero format.

Code
import { aq, op } from '@uwdata/arquero'
ojsdata_aq = aq.from(ojsdata)

ojsdata_aq
  .groupby('species')
  .filter(p => p.sepal_length > 5)
  .rollup({
    count: op.count(),
    avg_mass: op.average('sepal_length')
   })
  .view()