I Setting up a static server using R
Last updated: 2021-08-24 14:54:59
I.1 Introduction
This tutorial shows how to set up and start a static server using R. Installing and using R can be simpler and more straightforward compared to Python (Section 5.6.2).
The steps we will go through are as follows:
I.2 Installing R
To use R we first need to install it. R can be downloaded from the R-project website. The current version is 4.0.5. Once R is installed, we can open the default interface (RGui) with Start → All Programs → R → R x64 4.0.5 (Figure I.1).
A more advanced interface than the default one, called the RStudio, is often used when working with R. RStudio can be downloaded from the RStudio company website. The current version is 1.4.1106. Since starting a server is takes just few lines of code, RGui is is perfectly sufficient to keep things simple, and installing RStudio is not necessary.
I.3 Installing the servr
package
The “R console” panel in RGui is use to type R code and execute it, much like the JavaScript console (Section 3.4). The first thing we need to do is install the servr
package, which includes the static server function. Type the following expression into the R Console and press Enter:
install.packages("servr")
This is a one-time operation per computer (unless you need to update the package with a newer version).
I.4 Starting the server
To use the servr
package, you need to load it into the R session:
library(servr)
This needs to be done every time you start R and want to use the servr
package.
Next, navigate to the directory on your computer where you want to start the static server, using the setwd
function. For example, if the directory you wish to serve is located at C:\tmp\examples
, then you need to execute the following expression:
setwd("C:\\tmp\\examples")
Note that the path parts need to be separated with \\
, not with \
!
Finally, the server is started with the httd
function:
httd()
Running that last expression should open the browser window with the served directory automatically. Otherwise, you can open the served site by browsing to the following URL (Figure I.2):
http://localhost:4321/