-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy path1-01-intro-introduction.Rmd
158 lines (105 loc) Β· 7.88 KB
/
1-01-intro-introduction.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
\mainmatter
# (PART) Basics and Roadmap {-}
# Overview {#intro-overview}
```{r include=FALSE}
source("utils.R")
```
This book starts with a rationale for integrating JavaScript with R and supports it with examples, namely packages that use JavaScript and are available on CRAN\index{CRAN}. Then, we list the various ways in which one might go about making both languages work together. In the next chapter, we go over prerequisites and a review of concepts fundamental to fully understand the more advanced topics residing in the forthcoming chapters.
## Rationale {#intro-overview-rationale}
Why blend two languages seemingly so far removed from each other? Well, precisely because they are fundamentally different languages that each have their strengths and weaknesses; combining the two allows making the most of their consolidated advantages and circumvents their respective limitations to produce software altogether better for it.
Nevertheless, a fair reason to use JavaScript might be that the thing one wants to achieve in R has already been realised in JavaScript. Why reinvent the wheel when the solution already exists and that it can be made accessible from R? The R package [rmapshaper](https://github.com/ateucher/rmapshaper) [@R-rmapshaper] by Andy Teucher that integrates [mapshaper,](https://github.com/mbloch/mapshaper/) a library to edit geo-spatial-related files such as GeoJSON, or TopoJSON. JavaScript is by no means required to make those computations; they could be rewritten solely in R, but that would be vastly more laborious than wrapping the JavaScript API in R as done by the package rmapshaper.
```{r, warning=FALSE}
library(rmapshaper)
# get data
data(states, package = "geojsonio")
states_json <- geojsonio::geojson_json(
states,
geometry = "polygon",
group = "group"
)
states_sp <- geojsonio::geojson_sp(states_json)
# print shape file size
print(object.size(states_sp), units = "Mb")
# simplify with rmapshaper
states_sm <- rmapshaper::ms_simplify(states_sp, keep = 0.05)
# print reduced size
print(object.size(states_sm), units = "Mb")
```
Another great reason is that JavaScript can do things that R cannot, e.g., run in the browser. Therefore, one cannot natively create interactive visualisations with R. [Plotly](https://plotly-r.com/) [@R-plotly] by Carson Sievert packages the [plotly JavaScript library](https://plot.ly/) to let one create interactive visualisations solely from R code as shown in Figure \@ref(fig:plotly-basic-example).
```{r, warning=FALSE, message=FALSE, error=FALSE, eval=FALSE}
library(plotly)
plot_ly(diamonds, x = ~cut, color = ~clarity, width = "100%")
```
```{r plotly-basic-example, fig.pos="H", warning=FALSE, message=FALSE, error=FALSE, echo=FALSE, fig.cap='Basic htmlwidget example'}
library(plotly)
p <- plot_ly(diamonds, x = ~cut, color = ~clarity, width = "100%")
include_widget(p, "01-plotly.png")
```
Finally, JavaScript can work together with R to improve how we communicate insights. One of the many ways in which Shiny stands out is that it lets one create web applications solely from R code with no knowledge of HTML, CSS, or JavaScript, but that does not mean they can't extend Shiny---quite the contrary. The [waiter package](http://waiter.john-coene.com/) [@R-waiter] integrates a variety of JavaScript libraries to display loading screens in Shiny applications as in Figure \@ref(fig:intro-waiter).
```r
library(shiny)
library(waiter)
ui <- fluidPage(
use_waiter(), # include dependencies
actionButton("show", "Show loading for 3 seconds")
)
server <- function(input, output, session){
# create a waiter
w <- Waiter$new()
# on button click
observeEvent(input$show, {
w$show()
Sys.sleep(3)
w$hide()
})
}
shinyApp(ui, server)
```
```{r intro-waiter, fig.pos="H", echo=FALSE, fig.cap='Waiter screen'}
knitr::include_graphics("images/waiter.png")
```
Hopefully this makes a couple of great reasons and alluring examples to entice the reader to persevere with this book.
## Methods {#intro-methods}
Though perhaps not evident at first, all of the packages used as examples in the previous section interfaced with R very differently. As we'll discover, there are many ways in which one can blend JavaScript with R. Generally the way to go about it is dictated by the nature of what is to be achieved.
Let's list the methods available to us to blend JavaScript with R before covering each of them in-depth in their own respective chapter later in the book.
### V8 {#intro-v8}
[V8](https://github.com/jeroen/v8) by Jeroen Ooms is an R interface to Google's JavaScript engine. It will let you run JavaScript code directly from R and get the result back; it even comes with an interactive console. This is the way the rmapshaper package used in a previous example internally interfaces with the turf.js library.
```{r}
library(V8)
ctx <- v8()
ctx$eval("2 + 2") # this is evaluated in JavaScript!
```
### htmlwidgets {#intro-htmlwidgets}
[htmlwidgets](http://www.htmlwidgets.org/) [@R-htmlwidgets] specialises in wrapping JavaScript libraries that generate visual outputs. This is what packages such as plotly, [DT](https://rstudio.github.io/DT/) [@R-DT], [highcharter](http://jkunst.com/highcharter/) [@R-highcharter], and many more use to provide interactive visualisation with R.
It is by far the most popular integration out there: at the time of writing it has been downloaded nearly 10 million times from \index{CRAN}. It will therefore be covered extensively in later chapters.
### Shiny {#intro-shiny}
The Shiny framework allows creating applications accessible from web browsers\index{web browser} where JavaScript natively runs; it follows that JavaScript can run _alongside_ such applications. Often overlooked though, the two can also work _hand-in-hand_ as one can pass data from the R server to the JavaScript front end and vice versa. This is how the previously-mentioned package waiter internally works with R.
## Methods Amiss {#intro-amiss}
Note that there are also two other prominent ways one can use JavaScript with R that are not covered in this book. The main reason being that they require significant knowledge of specific JavaScript libraries, d3.js and React, and while these are themselves advanced uses of JavaScript, their integration with R via the following listed packages are relatively straightforward.
### reactR & vueR {#intro-reactr-vuer}
[ReactR](https://react-r.github.io/reactR/) [@R-reactR] is an R package that emulates very well htmlwidgets but specifically for the [React\index{React} framework](https://reactjs.org/). Unlike htmlwidgets, it is not limited to visual outputs and also provides functions to build inputs, e.g., a drop-down menu (like `shiny::selectInput`). The [reactable package](https://glin.github.io/reactable/) [@R-reactable] uses reactR to enable building interactive tables solely from R code as shown in Figure \@ref(fig:reactable-example).
```{r, eval=FALSE}
reactable::reactable(iris[1:5, ], showPagination = TRUE)
```
```{r reactable-example, fig.pos="H", echo=FALSE, fig.cap='reactable package example'}
t <- reactable::reactable(iris[1:5, ], showPagination = TRUE)
include_widget(t, "01-reactable.png")
```
There is also the package vueR [@R-vueR], which brings some of \index{Vue}Vue to R.
### r2d3 {#intro-r2d3}
[r2d3](https://rstudio.github.io/r2d3/) [@R-r2d3] by RStudio is an R package designed specifically to work with [d3.js](https://d3js.org/). It is similar to htmlwidgets but works rather differently, it allows create visualisations such as Figure \@ref(fig:r2d3).
```{r, eval=FALSE}
# https://rstudio.github.io/r2d3/articles/gallery/chord/
r2d3::r2d3(
data = matrix(round(runif(16, 1, 10000)), ncol = 4, nrow = 4),
script = "chord.js"
)
```
```{r r2d3, fig.pos="H", echo=FALSE, fig.cap='r2d3 basic example'}
# https://rstudio.github.io/r2d3/articles/gallery/chord/
r <- r2d3::r2d3(
data = matrix(round(runif(16, 1, 10000)), ncol = 4, nrow = 4),
script = "chord.js"
)
include_widget(r, "01-d3.png")
```