Build a simple ReactJS app
simple-react-app.RmdWe will create a simple ReactJS application that implements our favourite Old Faithful dataset. Of course, this is not a great use-case for Rserve as it would be more appropriate to use a REST API, but it is a simple example to demonstrate how to use Rserve with a front-end application.
Write the R code
The code is saved in a file called faithful-app.R, and
we can preview the results by calling the functions:
cat(readLines('faithful-app.R'), sep = '\n')
#> library(ts)
#>
#> get_hist <- ts_function(
#> function(bins = ts_integer(1)) {
#> h <- hist(faithful$waiting, breaks = bins, plot = FALSE)
#> data.frame(x = h$mids, y = h$density)
#> },
#> result = ts_dataframe(x = ts_numeric(0), y = ts_numeric(0))
#> )
#> get_smoother <- ts_function(
#> function(bandwidth = ts_numeric(1)) {
#> d <- density(faithful$waiting, bw = bandwidth)
#> data.frame(x = d$x, y = d$y)
#> },
#> result = ts_dataframe(x = ts_numeric(0), y = ts_numeric(0))
#> )
source('faithful-app.R')
get_hist$call(10)
#> x y
#> 1 42.5 0.0029411765
#> 2 47.5 0.0161764706
#> 3 52.5 0.0242647059
#> 4 57.5 0.0176470588
#> 5 62.5 0.0102941176
#> 6 67.5 0.0073529412
#> 7 72.5 0.0198529412
#> 8 77.5 0.0397058824
#> 9 82.5 0.0404411765
#> 10 87.5 0.0169117647
#> 11 92.5 0.0036764706
#> 12 97.5 0.0007352941That’s it! We’ll use ts_compile() later to create the
server code and Typescript schema for the app.
Create the React app
You should now be able to see the default Vite app running at
http://localhost:5173 (or similar, see the console
output).
Now install the rserve-ts and zod
packages:
Create the server code
We now use the ts_compile() function to create two
files:
-
faithful-app.rserve.Ris the file that will start the Rserve instance with your apps functions available. -
faithful-app.rserve.tscontains the TypeScript schema (using zod) that will let you use the R functions directly in the app like any other typescript function!
We’ll send these straight to the faithful-demo/src
directory.
ts_compile('faithful-app.R', filename = 'faithful-demo/src/faithful-app.rserve')