analythium / openfaas-rstats-templates

OpenFaaS templates for R
MIT License
19 stars 1 forks source link

Add R function examples #20

Closed psolymos closed 3 years ago

psolymos commented 3 years ago

Add examples for the 9 core templates. Examples 1-3 are JSON based ones. Examples 4-5 require mime type modifications.

Example 1: Hello

Simple Hello World example.

library(jsonlite)

hello <- function(x) {
    toJSON(paste0("Hello ", fromJSON(x), "!"))
}

hello('["World"]')
# ["Hello World!"]

Example 2: PCA

Calculate principal coordinates from an input matrix. This will demonstrate how to add dependency vegan.

library(vegan)
data(dune)
x <- dune
o <- rda(x)
s <- scores(o, 1:3)$sites

Example 3: classification

Train model and deploy scoring engine for multinomial classification using the iris data. Needs dependency and loading data (trained model)

library(e1071)
library(jsonlite)
data(iris)

s <- svm(Species ~ ., iris)

table(iris$Species, fitted(s))

# expect setosa
v <- '{"Sepal.Length":5.2,"Sepal.Width":3.4,"Petal.Length":1.5,"Petal.Width":0.2}'
z <- as.data.frame(fromJSON(v))
toJSON(predict(s, z))

Explore this from of-watchdog readme:

Files or models can be fetched and stored in /tmp/ as a one-off initialization task and used for all requests after that

Example 4: report

Report generation based on rmarkdown and whisker.

library(rmarkdown)
library(whisker)

template <-
'---
title: Template
output: {{format}}
---

# Hello {{name}}!

This document was auto generated on {{date}}.

{{#signature}}
xoxo
{{/signature}}'

data <- list( name = "Brett",
            date = as.character(Sys.Date()),
            signature=TRUE,
            filename="out",
            format="pdf_document")

v <- whisker.render(template, data)
cat(v)

f <- paste0(data$filename, ".Rmd")
#fout <- paste0(data$filename, ".", data$format)
writeLines(v, f)

render(f)

unlink(f)
unlink(paste0(data$filename, ".pdf"))

Example 5: ETL

Extract-Transform-Load example.

psolymos commented 3 years ago

Examples moved to their own repo: https://github.com/analythium/openfaas-rstats-examples