forked from Real-Currents/SveltR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtech.Rmd
195 lines (149 loc) · 5.87 KB
/
tech.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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
---
title: Tech
author: John
date: '2020-02-27'
draft: false
categories:
- R
tags:
- R Markdown
---
<div id="tech-app" role="main" style="width: 100%; min-width: 800px;">
</div>
# [SveltR](https://github.com/Real-Currents/SveltR)
## A blogdown boilerplate for creating truly epic visualizations
```{r setup, include=FALSE}
options(warn = -1)
working_dir <- getwd()
print(working_dir)
print(grepl("/content", getwd(), ignore.case = TRUE))
if (grepl("/content", getwd(), ignore.case = TRUE)) {
working_dir <- stringr::str_replace(getwd(), "/content", "")
setwd(working_dir)
print("")
}
if (!require("knitr")) {
install.packages("knitr")
library("knitr")
}
knitr::opts_chunk$set(cache = TRUE)
knitr::opts_chunk$set(echo = TRUE)
```
This is a boilerplate for using [blogdown (R Markdown x Hugo)](https://github.com/rstudio/blogdown/) as a static site generator and [SvelteJS](https://svelte.dev/) as your reactive app engine. This project is released under the [MIT license](LICENSE). Please make sure you understand its implications and guarantees.
<br />
## Enjoy!! 🦊
This page is the product of an R Markdown document and an embedded Svelte app. The `<div id="tech-app"></div>` HTML tag embedded in this page contains the "tech-app" id attribute which is a DOM element id that `TestApp.svelte` has been instructed to find in order to instantiate the interactive graphics above. To learn more about developing SvelteJS applications see <https://svelte.dev/tutorial/basics>. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
You can embed an R code chunk like this:
```{r echo}
print(mean(1 : 5))
Sys.getenv("R_HOME")
r_profiles <- c(file.path(Sys.getenv("R_HOME"), "etc", "Rprofile.site"),
file.path(Sys.getenv("R_HOME"), "etc", "Rprofile"),
file.path(Sys.getenv("R_HOME"), "library", "base", "R", "Rprofile") )
Filter(file.exists, r_profiles)
.libPaths()
```
<br />
## Including Plots
You can also embed (static) plots, for example:
```{r pressure, echo = FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot. Otherwise, the code chunk will be printed on the page, like this [`plotly`](https://plotly.com/r/getting-started/) example:
```{r plotly, echo = TRUE}
options(warn = -1)
if (!require("plotly")) {
install.packages(c("plotly"))
library(plotly)
}
fig <- plot_ly(midwest, x = ~percollege, color = ~state, type = "box")
fig
```
<div class="r-mapping">
Use R's geospatial packages to plot data on maps. For the following example, you will need to have installed the following native libraries on the host operating system:
pandoc gdal geos proj udunits2:
```{r mapping, echo = FALSE}
#options(warn=-1) # versions of GEOS runtime 3.7.2-CAPI-1.11.2 and GEOS at installation 3.7.1-CAPI-1.11.1 differ
options(warn = 0)
if (!require("maptools")) {
install.packages(c("maptools", "rgdal", "rgeos", "sf", "sp"))
} else {
options(warn=-1)
require(sp)
require(rgdal)
require(rgeos)
options(warn = 0)
require(maptools)
data(wrld_simpl)
xlim <- c(-130,-60)
ylim <- c(35,50)
plot(wrld_simpl,xlim=xlim,ylim=ylim,col='olivedrab3',bg='lightblue')
plot(wrld_simpl)
coords <- matrix(c(-122.92,-79.4, 49.277,43.66),ncol=2)
coords <- matrix(c(-122.92,-79.4, 49.277,43.66),ncol=2)
coords <- coordinates(coords)
spoints <- SpatialPoints(coords)
df <- data.frame(location=c("SFU","UofT"))
spointsdf <- SpatialPointsDataFrame(spoints,df)
plot(wrld_simpl) + plot(spointsdf,add=T,col=c('red','blue'),pch=16)
}
```
</div>
## Embedding JSON data in HTML
If the output target is HTML, R has some methods for turning R data into JavaScript or JSON data and printing the results within HTML tags:
```{r car_data}
head(mtcars)
```
The mtcars sample dataset printed above has been serialized to JSON and added to a `<script>` tag contained within a `<div id="car_data_in_html">`.
<div class="r-data">
```{r car_data_in_html, results = 'asis'}
require(jsonlite)
# print without tabs so R markdown will add it to the DOM tree of the resulting page
cat(paste('<div id="car_data_in_html"><script type="application/json">', toJSON(mtcars), '\n</script>\n</div>', sep=""))
```
```{r, echo = FALSE, results = 'asis'}
# add tabs to tags, to pre print code results
cat(paste('\n\t<div id="car_data_in_html">\n\t\t<script type="application/json">', toJSON(mtcars), '\n\t\t</script>\n\t</div>', sep=""))
```
</div>
Note the specification of the `type="application/json"` attribute, which prevents the browser from evaluating the contents of the `<script>` tag as JavaScript (if that is intended) and allows some other code block to call:
<script>
var data = JSON.parse(document.getElementById('car_data_in_html').children[0].innerHTML);
</script>
<br />
## Run Python with Reticulate
It is also possible to include Python code chunks in R Markdown, by first loading the `reticulate` package (in R):
```{r prepare_python, echo = TRUE}
# Load reticulate package for running python
if (!require("reticulate")) {
install.packages("reticulate")
reticulate::conda_python(envname = "r-reticulate")
reticulate::use_condaenv(condaenv = "r-reticulate", required = TRUE)
}
reticulate::py_install(c("matplotlib"))
py_sys <- import("sys")
print(py_sys$path)
cat(list.files(py_sys$path)[grepl("matplot", list.files(py_sys$path))])
```
... and then writing the python code;
```{python data_test}
data = {"foo": {"bar": "baz"}}
string = "Reticulate"
for index, letter in enumerate(string):
print((letter, index))
```
```{python pyplot}
import sys
sys.path
try:
import matplotlib.pyplot as plt
import numpy as np
# %matplotlib inline
# %config InlineBackend.figure_format = 'svg'
t = np.linspace(0, 20, 500)
plt.plot(t, np.sin(t))
plt.show()
except Exception as e:
print(e)
```