R data loader examples
Observable Framework supports data loaders written in R, by passing them to the Rscript command. The latter must be available on your $PATH. Any library used by your scripts must also be installed.
CSV
The data loader below reads in the penguins data from a local file, performs k-means clustering based on culmen (bill) length and depth, then outputs a CSV file the original penguins data enriched with cluster assignments.
Create a file in your project source root with the .csv.R double extension (for example, docs/data/my-data.csv.R), then paste the R code below to get started.
Access the output of the data loader from the client using FileAttachment:
const penguinKmeans = FileAttachment("data/penguin-kmeans.csv").csv({typed: true});
The file attachment name does not include the .R extension. We rely on Framework’s routing to run the appropriate data loader.
We can now display the dataset with the assigned clusters:
JSON
The data loader below accesses the text of War and Peace from the Gutenberg Project, finds the most common words by chapter, and returns a JSON.
Create a file in your project source root with the .json.R double extension (for example, docs/data/my-data.json.R), then paste the R code below to get started.
Access the output of the data loader from the client using FileAttachment:
const text = FileAttachment("data/tolstoy.json").json()
The file attachment name does not include the .R extension. We rely on Framework’s routing to run the appropriate data loader.
text
ZIP
The data loader below reads in the penguins data from a local file, performs multiple linear regression, then outputs multiple files (with model estimates and predictions) as a ZIP archive.
Create a file in your project source root with the .zip.R double extension (for example, docs/data/my-data.zip.R), then paste the R code below to get started.
The system function invokes the system command "zip - -r .", where:
zipis the command for zipping files-means the archive is output to standard output (required for data loaders)-r, the recursive option, means all files are added to the zip archive.compresses the current working directory
Access the output of the data loader from the client using FileAttachment:
const modelZip = FileAttachment("data/penguin-mlr.zip").zip();
The file attachment name does not include the .R extension. We rely on Framework’s routing to run the appropriate data loader.
You can then access individual files from the ZIP archive:
const modelEstimates = modelZip.file("estimates.csv").csv({typed: true});
modelEstimates
Alternatively, access individual files from the ZIP archive straightaway:
const modelPredictions = FileAttachment("data/penguin-mlr/predictions.csv").csv({typed: true})
modelPredictions