-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01_intro_rstudio.Rmd
395 lines (270 loc) · 15.6 KB
/
01_intro_rstudio.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# Introducción a R y RStudio
## R
- R: es gratis, de acceso libre, utilizado para muchos campos de trabajo, fuerte en la bioinformática a través de Bioconductor
- Instalación a través de CRAN: <https://cran.r-project.org/>
- Para explorar que se puede hacer con R:
- R Weekly <https://rweekly.org/>
- R Bloggers <https://www.r-bloggers.com/>
- Twitter <https://twitter.com/search?q=%23rstats&src=typed_query>
- Twitter en español <https://twitter.com/search?q=%23rstatsES&src=typed_query>
- TidyTuesday <https://twitter.com/search?q=%23TidyTuesday&src=typed_query>
- DatosDeMiercoles <https://twitter.com/search?q=%23datosdemiercoles&src=typed_query>
- Para pedir ayuda hay muchas opciones
- <https://lcolladotor.github.io/bioc_team_ds/how-to-ask-for-help.html>
- Material en el que estoy involucrado:
- <https://twitter.com/lcolladotor>
- <https://bsky.app/profile/lcolladotor.bsky.social>
- <https://www.youtube.com/c/LeonardoColladoTorres/playlists>
- LIBD rstats club <https://docs.google.com/spreadsheets/d/1is8dZSd0FZ9Qi1Zvq1uRhm-P1McnJRd_zxdAfCRoMfA/edit?usp=sharing>
- <https://twitter.com/CDSBMexico> y <https://twitter.com/LIBDrstats>
- <https://twitter.com/Bioconductor>
<img src="icon_192.png"/>
## GitHub
- Permite compartir código
- Se complementa con Git que es para tener un control de versiones de tu código
- <https://github.com/ComunidadBioInfo/cdsb2020/blob/master/presentaciones_flujos-de-trabajo/Introduccion-al-flujo-de-trabajo-orientado-a-proyectos.pdf>
- Puedes tener páginas web estáticas
- <https://pages.github.com/>
- <https://github.com/lcolladotor/rnaseq_LCG-UNAM_2024>. En especial <https://github.com/lcolladotor/rnaseq_LCG-UNAM_2024/tree/gh-pages> se convierte en <http://lcolladotor.github.io/rnaseq_LCG-UNAM_2024/>
- Página personal: <https://github.com/lcolladotor/lcolladotor.github.com> se convierte en <http://lcolladotor.github.io/>. Está todo hecho con <https://github.com/lcolladotor/lcolladotorsource>
- Tip: usen el mismo nombre de usuario en GitHub, Twitter, Gmail, etc.
- How to be a Modern Scientist: <https://lcolladotor.github.io/bioc_team_ds/how-to-be-a-modern-scientist.html>
## RStudio
- RStudio Desktop es gratis <http://www.rstudio.com/products/rstudio/download/preview/>
- Nos ayuda a realizar muchas cosas con R de forma más rápida
- Demo `rsthemes`
```{r install_rsthemes, eval = FALSE}
remotes::install_github(c(
"gadenbuie/rsthemes"
))
remotes::install_cran("suncalc")
rsthemes::install_rsthemes(include_base16 = TRUE)
```
```{r r_profile, eval = FALSE}
usethis::edit_r_profile()
## From https://www.garrickadenbuie.com/project/rsthemes/
if (interactive() && requireNamespace("rsthemes", quietly = TRUE)) {
# Set preferred themes if not handled elsewhere..
rsthemes::set_theme_light("Solarized Light {rsthemes}") # light theme
rsthemes::set_theme_dark("base16 Monokai {rsthemes}") # dark theme
rsthemes::set_theme_favorite(c(
"Solarized Light {rsthemes}",
"base16 Monokai {rsthemes}",
"One Dark {rsthemes}"
))
# Whenever the R session restarts inside RStudio...
setHook("rstudio.sessionInit", function(isNewSession) {
# Automatically choose the correct theme based on time of day
## Used rsthemes::geolocate() once
rsthemes::use_theme_auto(lat = 39.2891, lon = -76.5583)
}, action = "append")
}
## https://blog.rstudio.com/2013/06/10/rstudio-cran-mirror/
options(repos = c(CRAN = "https://cloud.r-project.org"))
```
- Es actualizado con bastante frecuencia
- RStudio cheatsheets <https://posit.co/resources/cheatsheets/>
- <https://posit.co/wp-content/uploads/2022/10/rstudio-ide-1.pdf>
- RStudio projects: usalos para organizar tu código
- <https://github.com/ComunidadBioInfo/cdsb2020/blob/master/presentaciones_flujos-de-trabajo/Trabajando-con-proyectos.pdf>
```{r proj, eval = FALSE}
usethis::create_project("~/rnaseq_2024_notas")
```
```{r create_setup, eval = FALSE}
## Start a setup file
usethis::use_r("01-notas.R")
```
O por ejemplo el archivo [02-visualizar-mtcars.R](https://github.com/lcolladotor/rnaseq_2022_notas_envivo/blob/master/R/02-visualizar-mtcars.R)
```{r create_01-visualizar-mtcars, eval = FALSE}
## Creemos el archivo R/02-visualizar-mtcars.R
usethis::use_r("02-visualizar-mtcars.R")
```
con el siguiente contenido:
```{r vis_mtcars, eval = FALSE}
library("sessioninfo")
library("here")
library("ggplot2")
## Hello world
print("Soy Leo")
## Directorios
dir_plots <- here::here("figuras")
dir_rdata <- here::here("processed-data")
## Crear directorio para las figuras y archivos
dir.create(dir_plots, showWarnings = FALSE)
dir.create(dir_rdata, showWarnings = FALSE)
## Hacer una imagen de ejemplo
pdf(file.path(dir_plots, "mtcars_gear_vs_mpg.pdf"),
useDingbats = FALSE
)
ggplot(mtcars, aes(group = gear, y = mpg)) +
geom_boxplot()
dev.off()
## Para reproducir mi código
options(width = 120)
sessioninfo::session_info()
```
- Un video de mi club de R sobre RStudio y el uso de `here`:
<iframe width="560" height="315" src="https://www.youtube.com/embed/XTuJ8vGnzBU" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen>
</iframe>
También hay videos en el [canal de YouTube de la CDSB](https://www.youtube.com/channel/UCHCdYfAXVzJIUkMoMSGiZMw) sobre `here` como pueden ver [aquí](https://www.youtube.com/channel/UCHCdYfAXVzJIUkMoMSGiZMw/search?query=here).
- Para una guía más detallada de cómo organizar tus archivos, revisa <https://lcolladotor.github.io/bioc_team_ds/organizing-your-work.html#.YflDV-rMJD8>. En particular, [LieberInstitute/template_project](https://github.com/LieberInstitute/template_project).
- Acá está la guía de mi equipo de configuración de R: <https://lcolladotor.github.io/bioc_team_ds/config-files.html#r-setup>.
- Configura `usethis` con GitHub vía <https://usethis.r-lib.org/articles/articles/git-credentials.html>
```{r use_git_init, eval = FALSE}
## Para poder conectar tu compu con GitHub
usethis::create_github_token() ## Abrirá una página web, escoje un nombre único
## y luego da click en el botón verde al final. Después copia el token
## (son 40 caracteres)
```
- Para Mac o Windows:
```{r gitcreds_set, eval = FALSE}
gitcreds::gitcreds_set() ## Ojo, copia el token, no tu password de git!
## Si no, terminaras en la situación descrita en
## https://github.com/r-lib/usethis/issues/1347
```
- Para Linux:
En el servidor de [RStudio de la LCG-UNAM](http://132.248.220.108:8787/) no funciona bien `gitcreds::gitcreds_set()` (porque esa función solo corre bien en macOS o winOS) así que tenemos que editar el archivo `.Renviron` donde nuestro token no se guarda de forma privada, y por lo cual hoy en día no es lo que recomienda [Jenny Bryan](https://twitter.com/JennyBryan). Pero es lo que funciona en este caso tal como lo hablamos con el autor de [`gitcreds` vía GitHub](https://github.com/r-lib/gitcreds/issues/29). Usando el siguiente comando podemos abrir el archivo `.Renviron`.
```{r edit_r_envir, eval = FALSE}
usethis::edit_r_environ()
```
Después guarden su token de GitHub usando la siguiente sintáxis (ojo con la línea en blanco al final, las mayúsculas al inicio, y el que no hay espacios antes y después del `=`).
```
GITHUB_PAT=TU_CLAVE_DE_40_LETRAS
```
Después de guardar el `.Renviron`, vayan a `Session` hasta arriba y reinicien la sesión de R para que se cargue el `.Renviron` antes de continuar.
- Continuemos con tu configuración de GitHub
```{r use_git_cont_parte1, eval = FALSE}
## Configura tu usuario de GitHub
usethis::edit_git_config()
```
```
[user]
name = Leonardo Collado Torres
email = lcolladotor@gmail.com
```
```{r use_git_cont_parte2, eval = FALSE}
## Para inicializar el repositorio de Git
usethis::use_git()
## Para conectar tu repositorio local de Git con los servidores de GitHub
usethis::use_github()
```
Resultado ejemplo: <https://github.com/lcolladotor/rnaseq_2021_notas>. El que hice en vivo está disponible vía <https://github.com/lcolladotor/rnaseq_2024_notas_en_vivo>.
Una vez que termines, agrega la liga al repositorio con tus notas del curso en el [la página del curso](https://cursos.lcg.unam.mx/course/view.php?id=197#section-2).
## Material del curso
- Pueden descargar la versión estática con `usethis::use_course('lcolladotor/rnaseq_LCG-UNAM_2024')`
- Pueden verlo en línea a través de [**lcolladotor.github.io/rnaseq_LCG-UNAM_2024**](http://lcolladotor.github.io/rnaseq_LCG-UNAM_2024)
- Pueden **clonarlo** desde GitHub de tal forma que podrán actualizarlo fácilmente usando *git pull*
```{bash clone_course, eval = FALSE}
git clone https://github.com/lcolladotor/rnaseq_LCG-UNAM_2024.git
## Si tienen su SSH key configurarda pueden usar
## Info sobre SSH keys de GitHub:
## https://docs.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent
git clone git@github.com:lcolladotor/rnaseq_LCG-UNAM_2024.git
```
O desde R con:
```{r clone_repo, eval = FALSE}
## Opción más nueva:
library("gert")
repo <- git_clone(
"https://github.com/lcolladotor/rnaseq_LCG-UNAM_2024",
"~/Desktop/rnaseq_LCG-UNAM_2024"
)
setwd(repo)
## Otra opción:
git2r::clone(
"https://github.com/lcolladotor/rnaseq_LCG-UNAM_2024",
"~/Desktop/rnaseq_LCG-UNAM_2024"
)
```
## Actividad postcards
*Impartida por [Melissa Mayén Quiroz](https://melii99.github.io/)*
30/01/2024
<iframe class="speakerdeck-iframe" frameborder="0" src="https://speakerdeck.com/player/b7d3bbee06d14a548a664e76ea9110d8" title="Updating spatialLIBD: from SingleCellExperiment to VisiumExperiment classes" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true" style="border: 0px; background: padding-box padding-box rgba(0, 0, 0, 0.1); margin: 0px; padding: 0px; border-radius: 6px; box-shadow: rgba(0, 0, 0, 0.2) 0px 5px 40px; width: 560px; height: 420px;" data-ratio="1.3333333333333333">
</iframe>
<iframe width="560" height="315" src="https://www.youtube.com/embed/Q6eRD8Nyxfk" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen>
</iframe>
<iframe width="560" height="315" src="https://www.youtube.com/embed/0S_tRne5UNk" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen>
</iframe>
Repositorio de GitHub para la actividad de Postcards: <https://github.com/Melii99/rnaseq_2024_postcards>
En el mismo se encuentran las diapositivas: <https://github.com/Melii99/rnaseq_2024_postcards/blob/master/Postcards_Diapositivas.pdf>
### Create Beautiful, Simple Personal Websites
*A collection of R Markdown templates for creating simple and easy to personalize single page websites.*
"El objetivo del paquete es facilitar que cualquier persona pueda crear un sitio web personal de una sola página con un documento R Markdown."
- Autor: Sean Kross [aut, cre]
- Maintainer: Sean Kross \<sean at seankross.com\>
- <https://CRAN.R-project.org/package=postcards>
- GitHub: <https://github.com/seankross/postcards>
- Similar a <https://pages.github.com/>
- Tu página web debe describir decir algo sobre ti, tus intereses, y tus proyectos además de cómo contactarte
Algunos ejemplos:
- <https://amy-peterson.github.io/> vía <https://github.com/amy-peterson/amy-peterson.github.com>
- <http://jtleek.com/> vía <https://github.com/jtleek/jtleek.github.io>
- <http://aejaffe.com/> vía <https://github.com/andrewejaffe/andrewejaffe.github.io>
- <https://hadley.nz/> vía <https://github.com/hadley/hadley.github.com>
- <https://emarquezz.github.io/> vía <https://github.com/emarquezz/emarquezz.github.io>
- <https://bpardo99.github.io/> vía <https://github.com/bpardo99/bpardo99.github.io>
- <https://daianna21.github.io/> vía <https://github.com/daianna21/daianna21.github.io>.
- https://reneegf.github.io/ vía https://github.com/reneegf/reneegf.github.io.
- https://cfausto.github.io/ vía https://github.com/cfausto/cfausto.github.io/.
- https://davidgonilski.github.io/ vía https://github.com/davidgonilski/davidgonilski.github.io.
También pueden revisar https://lcolladotor.github.io/jhustatcomputing2023/projects/project-0/.
### Instalación
```{r, eval=FALSE}
## Puedes instalar Postcards con el siguiente comando:
install.packages("postcards")
## O puedes instalar la última versión en desarrollo:
remotes::install_github("seankross/postcards@main")
```
### Plantillas
Postcards incluye cinco plantillas: Jolla, Jolla Blue, Trestles, Onofre y Solana. Cada sitio está optimizado para ser visualizado tanto en computadoras de escritorio como en dispositivos móviles. El objetivo del paquete es facilitar que cualquier persona pueda crear un sitio web personal de una sola página con un documento R Markdown





Para comenzar a personalizar una de estas plantillas, debes crear un nuevo proyecto.
### Crear un nuevo proyecto en RStudio (selección interactiva)
Si usas RStudio:
- selecciona "File", "New Project"...
- Elige "New Directory", "Postcards Website"
- Ingresar un nombre de directorio para tu proyecto en RStudio ("Tu_Usuario.github.io")
- Elegir una de las plantillas desde un menú desplegable
Selecciona "Create Project" después de elegir un nombre para la carpeta que contendrá tu sitio. Esta carpeta contendrá dos archivos importantes:
- Un documento R Markdown con el contenido de tu sitio
- Una foto de muestra que debes reemplazar"
### Crear un nuevo proyecto
```{r, eval=FALSE}
## Crearun nuevo proyecto
usethis::create_project("Su_Usuario.github.io")
```
### Configurar Git y GitHub
Para poder guardar los cambios es necesario configurar Git y GitHub
```{r, eval=FALSE}
## Configurar Git y GitHub
usethis::use_git() # Reiniciar la sesión
usethis::use_github()
```
### Elegir una plantilla
```{r, eval=FALSE}
## Elegir solo una plantilla (la que más te guste)
postcards::create_postcard(template = "jolla")
postcards::create_postcard(template = "jolla-blue")
postcards::create_postcard(template = "trestles")
postcards::create_postcard(template = "onofre")
postcards::create_postcard(template = "solana")
```
De esta manera también se obtienen los 2 archivos importantes:
- Un documento R Markdown con el contenido de tu sitio
- Una foto de muestra que debes reemplazar
### Editar con su información
- Ahora deberán editar el documento R Markdown con su información y reemplazar la imágen con la que elijan :)
- Llenen su información usando el formato `Markdown`. Por ejemplo <https://github.com/andrewejaffe/andrewejaffe.github.io/blob/master/index.Rmd#L17-L31>.
- Agreguen sus perfiles estilo <https://github.com/andrewejaffe/andrewejaffe.github.io/blob/master/index.Rmd#L7-L12>
### Desplegar la página
Para compilar el archivo HTML autocontenido para el sitio:
- En RStudio puedes utilizar el botón "Knit"
o directamente:
```{r, eval=FALSE}
## Desplegar la página GitHub
rmarkdown::render("index.Rmd")
```