diff --git a/crowdin.yml b/crowdin.yml new file mode 100644 index 000000000..0ba000bdd --- /dev/null +++ b/crowdin.yml @@ -0,0 +1,29 @@ +preserve_hierarchy: true + +files: + - source: /episodes/*.Rmd + dest: /episodes/%file_name%.md + type: md + translation: /locale/%two_letters_code%/episodes/%original_file_name% + - source: /episodes/*.md + translation: /locale/%two_letters_code%/episodes/%original_file_name% + - source: /instructors/*.md + translation: /locale/%two_letters_code%/instructors/%original_file_name% + - source: /learners/*.md + translation: /locale/%two_letters_code%/learners/%original_file_name% + - source: /profiles/*.md + translation: /locale/%two_letters_code%/profiles/%original_file_name% + - source: /CODE_OF_CONDUCT.md + translation: /locale/%two_letters_code%/%original_file_name% + - source: /config.yaml + translation: /locale/%two_letters_code%/%original_file_name% + - source: /CONTRIBUTING.md + translation: /locale/%two_letters_code%/%original_file_name% + - source: /LICENSE.md + translation: /locale/%two_letters_code%/%original_file_name% + - source: /README.md + translation: /locale/%two_letters_code%/%original_file_name% + - source: /index.md + translation: /locale/%two_letters_code%/%original_file_name% + - source: /links.md + translation: /locale/%two_letters_code%/%original_file_name% \ No newline at end of file diff --git a/locale/es/CODE_OF_CONDUCT.md b/locale/es/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..39642f9b9 --- /dev/null +++ b/locale/es/CODE_OF_CONDUCT.md @@ -0,0 +1,12 @@ +--- +title: Código de conducta del colaborador +--- + +Como contribuyentes y mantenedores de este proyecto, +nos comprometemos a seguir el [Código de conducta de Carpinterías][coc]. + +Los casos de comportamiento abusivo, acosador o de otro modo inaceptable +pueden denunciarse siguiendo nuestras [directrices de denuncia][coc-reporting]. + +[coc-reporting]: https://docs.carpentries.org/topic_folders/policies/incident-reporting.html +[coc]: https://docs.carpentries.org/topic_folders/policies/code-of-conduct.html diff --git a/locale/es/CONTRIBUTING.md b/locale/es/CONTRIBUTING.md new file mode 100644 index 000000000..3808ec0b7 --- /dev/null +++ b/locale/es/CONTRIBUTING.md @@ -0,0 +1,151 @@ +# Contribuyendo + +[Software Carpentry][swc-site] y [Data Carpentry][dc-site] son proyectos de código abierto, +y agradecemos contribuciones de todo tipo: +nuevas lecciones, +Se aceptan correcciones al material existente, +informes de errores, +y revisiones de los cambios propuestos. + +## Acuerdo de colaborador + +Al contribuir, +, aceptas que podemos redistribuir tu trabajo bajo [nuestra licencia](LICENSE.md). +A cambio, +abordaremos sus problemas y/o evaluaremos su propuesta de cambio lo antes posible, +y le ayudaremos a convertirse en miembro de nuestra comunidad. +Todos los involucrados en [Software Carpentry][swc-site] y [Data Carpentry][dc-site] +aceptan cumplir con nuestro [código de conducta](CONDUCT.md). + +## Cómo contribuir + +La forma más fácil de comenzar es presentar un problema +para informarnos sobre un error ortográfico, +alguna redacción incómoda, +o un error factual. +Esta es una buena manera de presentarse +y conocer a algunos de los miembros de nuestra comunidad. + +1. Si no tienes una cuenta de [GitHub][github], + puedes \[enviarnos comentarios por correo electrónico]\[contacto]. + Sin embargo, + podremos responder más rápidamente si utiliza uno de los otros métodos que se describen a continuación. + +2. Si tienes una cuenta [GitHub][github], + o estás dispuesto a [crear una][github-join], + pero no sabes cómo usar Git, + Puede informar problemas o sugerir mejoras \[creando un problema]\[problemas]. + Esto nos permite asignar el elemento a alguien + y responderle en una discusión encadenada. + +3. Si se siente cómodo con Git, + y le gustaría agregar o cambiar material, + , puede enviar una solicitud de extracción (PR). + Las instrucciones para hacer esto se [incluyen a continuación] (#using-github). + +## Dónde contribuir + +1. Si desea cambiar esta lección, + , trabaje en , + , que se puede ver en . + +2. Si desea cambiar la lección de ejemplo, + , trabaje en , + , que documenta el formato de nuestras lecciones + y se puede ver en . . + +3. Si desea cambiar la plantilla utilizada para los sitios web de los talleres, + trabaje en . + La página de inicio de ese repositorio explica cómo configurar sitios web de talleres, + , mientras que las páginas adicionales en + brindan más antecedentes sobre nuestras opciones de diseño. + +4. Si desea cambiar archivos de estilo CSS, herramientas, + o texto estándar HTML para lecciones o talleres almacenados en `_includes` o `_layouts`, + , trabaje en . + +## Qué contribuir + +There are many ways to contribute, +from writing new exercises and improving existing ones +to updating or filling in the documentation +and submitting [bug reports][issues] +about things that don't work, aren't clear, or are missing. +Si está buscando ideas, +consulte \[la lista de problemas para este repositorio]\[problemas], +o los problemas para [Data Carpentry][dc-issues] +y proyectos de [Carpintería de Software][swc-issues]. + +Los comentarios sobre problemas y revisiones de solicitudes de extracción son igualmente bienvenidos: +somos más inteligentes juntos que solos. +Las reseñas de principiantes y recién llegados son particularmente valiosas: +es fácil para las personas que han estado usando estas lecciones por un tiempo +olvidar lo impenetrable que puede ser parte de este material, +tan fresco Los ojos siempre son bienvenidos. + +## Qué _no_ contribuir + +Nuestras lecciones ya contienen más material del que podemos cubrir en un taller típico, +, por lo que generalmente _no_ buscamos más conceptos o herramientas para agregarles. +Como regla general, +si quieres presentar una idea nueva, +debes (a) estimar cuánto tiempo tomará enseñar +y (b) explicar lo que tomaría para hacerle espacio. +El primero anima a los contribuyentes a ser honestos acerca de los requisitos; +el segundo, pensar mucho en las prioridades. + +Tampoco buscamos ejercicios u otro material que solo se ejecute en una plataforma. +Nuestros talleres suelen contener una combinación de usuarios de Windows, macOS y Linux; +para que sean utilizables, +nuestras lecciones deben funcionar igualmente bien en los tres. + +## Usando GitHub + +Si eliges contribuir a través de GitHub, +es posible que desees consultar +\[Cómo contribuir a un proyecto de código abierto en GitHub]\[cómo contribuir]. +En breve: + +1. La copia publicada de la lección se encuentra en la rama `gh-pages` del repositorio + (para que GitHub la regenere automáticamente). + Cree todas las ramas a partir de eso, + y combine la rama `gh-pages` del [repositorio maestro][repo] con su rama `gh-pages` + antes de comenzar a trabajar. + Por favor _no_ trabaje directamente en su rama `gh-pages`, + ya que eso le dificultará trabajar en otras contribuciones. + +2. Usamos [GitHub flow][github-flow] para gestionar los cambios: + 1. Cree una nueva rama en su copia de escritorio de este repositorio para cada cambio significativo. + 2. Confirme el cambio en esa rama. + 3. Empuje esa rama a su bifurcación de este repositorio en GitHub. + 4. Envíe una solicitud de extracción desde esa rama al \[repositorio maestro]\[repositorio]. + 5. Si recibe comentarios, + realice cambios en su escritorio y envíelos a su sucursal en GitHub: + la solicitud de extracción se actualizará automáticamente. + +Cada lección tiene dos mantenedores que revisan los problemas y generan solicitudes +o alientan a otros a hacerlo. +Los mantenedores son voluntarios de la comunidad, +y tienen la última palabra sobre lo que se integra en la lección. + +## Otros recursos + +La discusión general sobre [Software Carpentry][swc-site] y [Data Carpentry][dc-site] +ocurre en la \[lista de correo de discusión]\[lista de discusión], +, donde todos son bienvenidos unir. +También puede \[comunicarse con nosotros por correo electrónico]\[contactar]. + +[contact]: +[dc-issues]: +[dc-lessons]: http://datacarpentry.org/lessons/ +[dc-site]: http://datacarpentry.org/ +[discuss-list]: http://lists.software-carpentry.org/listinfo/discuss +[github]: http://github.com +[github-flow]: https://guides.github.com/introduction/flow/ +[github-join]: https://github.com/join +[how-contribute]: https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github +[issues]: https://github.com/swcarpentry/shell-novice/issues/ +[repo]: https://github.com/swcarpentry/shell-novice/ +[swc-issues]: https://github.com/issues?q=user%3Aswcarpentry +[swc-lessons]: http://software-carpentry.org/lessons/ +[swc-site]: http://software-carpentry.org/ diff --git a/locale/es/LICENSE.md b/locale/es/LICENSE.md new file mode 100644 index 000000000..ac5c86cfd --- /dev/null +++ b/locale/es/LICENSE.md @@ -0,0 +1,82 @@ +--- +title: Licencias +--- + +## Material didáctico + +Todo el material instructivo de Carpintería de software, Carpintería de datos y Carpintería de biblioteca está +disponible bajo la [licencia Creative Commons Attribution +][cc-by-human]. El siguiente es un resumen legible por humanos de +(y no un sustituto de) la [texto legal completo de la licencia CC BY 4.0 +][cc-by-legal]. + +Estas libre: + +- **Compartir**---copiar y redistribuir el material en cualquier medio o formato +- **Adaptar**---remezclar, transformar y construir sobre el material + +para cualquier fin, incluso comercial. + +El licenciante no puede revocar estas libertades siempre y cuando cumpla con los términos de la licencia +. + +Bajo los siguientes términos: + +- **Atribución**---Debes dar el crédito apropiado (mencionando que + tu trabajo se deriva de un trabajo con Copyright © Software + Carpintería y, cuando sea práctico, vinculando a + http\://software-carpentry.org/), proporcione un [enlace a la licencia + ][cc-by-human] e indique si se realizaron cambios. Puede hacerlo + de cualquier manera razonable, pero no de ninguna manera que sugiera que el + licenciante lo respalda a usted o su uso. + +**Sin restricciones adicionales**---No puede aplicar términos legales ni +medidas tecnológicas que restrinjan legalmente a otros hacer +cualquier cosa que la licencia permita. En el entendido de que: + +Avisos: + +- No tiene que cumplir con la licencia para elementos del material + en el dominio público o donde su uso esté permitido por una excepción o limitación + aplicable. +- No se dan garantías. Es posible que la licencia no le otorgue todos los + permisos necesarios para el uso previsto. Por ejemplo, otros + derechos como publicidad, privacidad o derechos morales pueden limitar la forma en que usted + utiliza el material. + +## Software + +Excepto que se indique lo contrario, los programas de ejemplo y otro software +proporcionado por Software Carpentry y Data Carpentry están disponibles bajo la +[OSI][osi] aprobada +\[licencia MIT] \[mit-licencia]. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +El aviso de derechos de autor anterior y este aviso de permiso se incluirán +en todas las copias o partes sustanciales del Software. + +EL SOFTWARE SE PROPORCIONA "TAL CUAL", SIN GARANTÍA DE NINGÚN TIPO, +EXPRESA O IMPLÍCITA, INCLUYENDO PERO NO LIMITADO A LAS GARANTÍAS DE +COMERCIABILIDAD, IDONEIDAD PARA UN PROPÓSITO PARTICULAR Y +NO INFRACCIÓN. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +## Marca comercial + +"Software Carpentry" y "Data Carpentry" y sus respectivos logotipos +son marcas comerciales registradas de [Community Initiatives][ci]. + +[cc-by-human]: https://creativecommons.org/licenses/by/4.0/ +[cc-by-legal]: https://creativecommons.org/licenses/by/4.0/legalcode +[mit-license]: https://opensource.org/licenses/mit-license.html +[ci]: http://communityin.org/ +[osi]: https://opensource.org diff --git a/locale/es/README.md b/locale/es/README.md new file mode 100644 index 000000000..2cf83be66 --- /dev/null +++ b/locale/es/README.md @@ -0,0 +1,75 @@ +# Introducción al análisis de datos genómicos con R y Bioconductor + +[![Crea una cuenta de Slack con nosotros](https://img.shields.io/badge/Create_Slack_Account-The_Carpentries-071159.svg)](https://swc-slack-invite.herokuapp.com/) + +## Contribuyendo + +¡Agradecemos todas las contribuciones para mejorar la lección! Los mantenedores +harán todo lo posible para ayudarlo si tiene alguna pregunta, inquietud o +experimenta alguna dificultad en el camino. + +Nos gustaría pedirle que se familiarice con nuestra Guía de contribución + y eche un vistazo a las \[directrices +más detalladas]\[ejemplo de lección] sobre el formato adecuado. , formas de renderizar la lección +localmente e incluso cómo escribir nuevos episodios. + +Consulte la lista actual de [problemas][FIXME] para obtener ideas sobre cómo +contribuir a este repositorio. Para hacer tu contribución, utilizamos +el flujo de GitHub, que está muy bien explicado en el capítulo +[Contribuyendo a un proyecto +](http://git-scm.com/ book/en/v2/GitHub-Contributing-to-a-Project) +en Pro Git por Scott Chacon. + +Busque la etiqueta +![good\_first\_issue](https://img.shields.io/badge/-good%20first%20issue-gold.svg). Este +indica que los mantenedores agradecerán una solicitud de extracción que solucione este problema +. + +## Enlaces útiles + +- Si va a desarrollar material didáctico por primera vez + de acuerdo con nuestros principios de diseño, considere leer el + [Manual de desarrollo curricular de carpintería][cdh] +- Consulte el sitio web \[Ejemplo de lección] \[ejemplo de lección] para obtener más información sobre + trabajar con la plantilla de lección + +## equipo de lección + +Esta lección ha sido desarrollada y mantenida actualmente por + +- Laurent Gatto (mantenedor) +- Charlotte Sonson +- Jenny Drnevich +- Roberto Castelo +- Kevin Rue Albert + +También nos gustaría reconocer las contribuciones de: + +- Oliver Crook, Sarah Kaspar, Nick Hirschmueller, Lisa Breckels y Maria Doyle por sus contribuciones durante el taller de introducción de bioconductores en Heidelberg, como parte de EuroBioc2021 |> 2022. +- Axelle Loriot, Marco Chiapelle, Manon Martin y Toby Hodges por sus diversas contribuciones y debates. +- lmsimp, alorot, manonmartin, mchiapello, stavares843, JennyZadeh, csdaw, ninja-1337, fursham-h, lagerratrobe, fmichonneau, federicomarini, tobyhodges para solicitudes de extracción. + +Si hemos contribuido pero te extrañamos, disculpas y no dudes en agregarte con un PR. + +## Autores + +Puede encontrar una lista de contribuyentes a la lección en [AUTORES](AUTORES) + +## Citación + +Para citar esta lección, consulte con [CITACIÓN](CITACIÓN) + +[lesson-example]: https://carpentries.github.io/lesson-example +[cdh]: https://cdh.carpentries.org + +## Pruebas localmente + +Para realizar la prueba localmente, ejecute lo siguiente en el directorio de lecciones: + +```r +papel de lija::servir() +``` + +Para obtener más detalles, consulte las [instrucciones de instalación del banco de trabajo +] (https://carpentries.github.io/workbench/#installation). + diff --git a/locale/es/config.yaml b/locale/es/config.yaml new file mode 100644 index 000000000..ee22ebf6d --- /dev/null +++ b/locale/es/config.yaml @@ -0,0 +1,61 @@ +#------------------------------------------------------------ +#Values for this lesson. +#------------------------------------------------------------ +#Which carpentry is this (swc, dc, lc, or cp)? +#swc: Software Carpentry +#dc: Data Carpentry +#lc: Library Carpentry +#cp: Carpentries (to use for instructor training for instance) +#incubator: The Carpentries Incubator +carpentry: 'incubadora' +#Overall title for pages. +title: 'Introducción al análisis de datos con R y Bioconductor' +#Date the lesson was created (YYYY-MM-DD, this is empty by default) +created: '2020-09-14' +#Comma-separated list of keywords for the lesson +keywords: 'software, datos, lección, Las Carpinterías' +#Life cycle stage of the lesson +#possible values: pre-alpha, alpha, beta, stable +life_cycle: 'estable' +#License of the lesson +license: 'CC-BY 4.0' +#Link to the source repository for this lesson +source: 'https://github.com/carpentries-incubator/bioc-intro' +#Default branch of your lesson +branch: 'principal' +#Who to contact if there are any issues +contact: 'laurent.gatto@uclouvain.be' +#Navigation ------------------------------------------------ +#Use the following menu items to specify the order of +#individual pages in each dropdown section. Leave blank to +#include all pages in the folder. +#Example ------------- +#episodes: +#- introduction.md +#- first-steps.md +#learners: +#- setup.md +#instructors: +#- instructor-notes.md +#profiles: +#- one-learner.md +#- another-learner.md +#Order of episodes in your lesson +episodes: + - 10-organización-de-datos.Rmd + - 20-r-rstudio.Rmd + - 23-empezando-con-r.Rmd + - 25-empezando-con-datos.Rmd + - 30-dplyr.Rmd + - 40-visualización.Rmd + - 60-siguientes-pasos.Rmd +#Information for Learners +learners: +#Information for Instructors +instructors: +#Learner Profiles +profiles: +#Customisation --------------------------------------------- +#This space below is where custom yaml items (e.g. pinning +#sandpaper and varnish versions) should live +url: 'https://carpentries-incubator.github.io/bioc-intro' diff --git a/locale/es/episodes/10-data-organisation.Rmd b/locale/es/episodes/10-data-organisation.Rmd new file mode 100644 index 000000000..62d0154a3 --- /dev/null +++ b/locale/es/episodes/10-data-organisation.Rmd @@ -0,0 +1,832 @@ +--- +source: Rmd +title: Organización de datos con hojas de cálculo +teaching: 30 +exercises: 30 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Aprenda sobre las hojas de cálculo, sus fortalezas y debilidades. +- ¿Cómo damos formato a los datos en hojas de cálculo para un uso eficaz de los datos? +- Obtenga información sobre los errores comunes de las hojas de cálculo y cómo corregirlos. +- Organice sus datos de acuerdo con los principios de datos ordenados. +- Obtenga información sobre los formatos de hojas de cálculo basados en texto, como los formatos separados por comas (CSV) o separados por tabulaciones (TSV). + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- ¿Cómo organizar datos tabulares? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +> Este episodio se basa en la lección _Análisis de datos y +> Visualización en R para ecologistas_ de Data Carpentries. + +## Programas de hoja de cálculo + +**Pregunta** + +- ¿Cuáles son los principios básicos para usar hojas de cálculo para una buena organización de datos + ? + +**Objetivo** + +- Describir las mejores prácticas para organizar datos para que las computadoras puedan hacer + el mejor uso de los conjuntos de datos. + +**Punto clave** + +- Una buena organización de los datos es la base de cualquier proyecto de investigación. + +Una buena organización de los datos es la base de su proyecto de investigación +. La mayoría de los investigadores tienen datos o los ingresan en +hojas de cálculo. Los programas de hojas de cálculo son interfaces gráficas +muy útiles para diseñar tablas de datos y manejar datos muy básicos +funciones de control de calidad. Ver también @Broman:2018. + +### Esquema de hoja de cálculo + +Las hojas de cálculo son buenas para la entrada de datos. Por lo tanto, tenemos muchos datos +en hojas de cálculo. Gran parte de su tiempo como investigador lo dedicará a +esta etapa de "disputación de datos". No es lo más divertido, pero es +necesario. Le enseñaremos cómo pensar en la organización de datos y +algunas prácticas para una gestión de datos más eficaz. + +### Lo que esta lección no te enseñará + +- Cómo hacer _estadísticas_ en una hoja de cálculo +- Cómo hacer _trazar_ en una hoja de cálculo +- Cómo _escribir código_ en programas de hojas de cálculo + +Si desea hacer esto, una buena referencia es Head First +Excel, +publicado por O'Reilly. + +### ¿Por qué no enseñamos análisis de datos en hojas de cálculo? + +- El análisis de datos en hojas de cálculo suele requerir mucho trabajo manual + . Si desea cambiar un parámetro o ejecutar un análisis con un + nuevo conjunto de datos, normalmente tendrá que rehacer todo a mano. (Sabemos + que puedes crear macros, pero mira el siguiente punto). + +- También es difícil rastrear o reproducir análisis estadísticos o gráficos + realizados en programas de hojas de cálculo cuando desea volver a + su trabajo o alguien solicita detalles de su análisis. + +Hay muchos programas de hojas de cálculo disponibles. Dado que la mayoría de los participantes +utilizan Excel como su programa principal de hoja de cálculo, esta lección +utilizará ejemplos de Excel. Un programa de hoja de cálculo gratuito que también se puede utilizar +es LibreOffice. Los comandos pueden diferir un poco entre programas, +pero la idea general es la misma. + +Los programas de hojas de cálculo abarcan muchas de las cosas que necesitamos poder hacer +como investigadores. Podemos usarlos para: + +- Entrada de datos +- Organizar datos +- Subcomponer y ordenar datos +- Estadísticas +- Graficado + +Los programas de hojas de cálculo utilizan tablas para representar y mostrar datos. Los datos +formateados como tablas también son el tema principal de este capítulo, y +veremos cómo organizar los datos en tablas de una manera estandarizada para +garantizar un análisis posterior eficiente. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: discute los siguientes puntos con tu vecino. + +- ¿Has utilizado hojas de cálculo en tus investigaciones, cursos, + o en casa? +- ¿Qué tipo de operaciones hacéis en hojas de cálculo? +- ¿Para cuáles crees que son buenas las hojas de cálculo? +- ¿Has hecho accidentalmente algo en un programa de hoja de cálculo que te hizo + frustrado o triste? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +### Problemas con las hojas de cálculo + +Las hojas de cálculo son buenas para ingresar datos, pero en realidad tendemos a +usar programas de hojas de cálculo para mucho más que ingresar datos. Los usamos +para crear tablas de datos para publicaciones, para generar estadísticas resumidas +y hacer cifras. + +Generating tables for publications in a spreadsheet is not +optimal - often, when formatting a data table for publication, we're +reporting key summary statistics in a way that is not really meant to +be read as data, and often involves special formatting +(merging cells, creating borders, making it pretty). Le recomendamos que +realice este tipo de operación dentro de su software de edición de documentos. + +Las dos últimas aplicaciones, que generan estadísticas y cifras, deben usarse +con precaución: debido a la naturaleza gráfica, de arrastrar y soltar, de los programas de hojas de cálculo +, puede ser muy difícil, si no imposible, +replica tus pasos (y mucho menos vuelve sobre los de cualquier otra persona), especialmente si tus estadísticas o cifras de +requieren que hagas cálculos más complejos. Además, +al hacer cálculos en una hoja de cálculo, es fácil aplicar accidentalmente una fórmula +ligeramente diferente a varias celdas adyacentes. Cuando se utiliza un programa de estadísticas basado en línea de comandos +como R o SAS, es prácticamente +imposible aplicar un cálculo a una observación en su conjunto de datos +pero no a otra, a menos que esté haciendo a propósito. + +### Uso de hojas de cálculo para la entrada y limpieza de datos. + +En esta lección, asumiremos que lo más probable es que esté utilizando Excel como +su programa de hoja de cálculo principal; hay otros (gnumeric, Calc +de OpenOffice) y su funcionalidad es similar, pero Excel parece +ser el programa más utilizado por biólogos e investigadores biomédicos. + +En esta lección vamos a hablar de: + +1. Formatear tablas de datos en hojas de cálculo +2. Problemas de formato +3. Exportar datos + +## Formatear tablas de datos en hojas de cálculo + +**Preguntas** + +- ¿Cómo damos formato a los datos en hojas de cálculo para un uso eficaz de los datos? + +**Objetivos** + +- Describir las mejores prácticas para la entrada y formato de datos en + hojas de cálculo. + +- Aplique las mejores prácticas para organizar variables y observaciones en una hoja de cálculo + . + +**Puntos clave** + +- Nunca modifique sus datos sin procesar. Siempre haga una copia antes de realizar + cambios. + +- Realice un seguimiento de todos los pasos que sigue para limpiar sus datos en un + archivo de texto sin formato. + +- Organice sus datos de acuerdo con los principios de datos ordenados. + +El error más común que se comete es tratar los programas de hojas de cálculo como cuadernos de laboratorio +, es decir, confiar en el contexto, las notas al margen, el diseño espacial +de los datos y los campos para transmitir información. Como humanos, podemos +(generalmente) interpretar estas cosas, pero las computadoras no ven la información +de la misma manera, y a menos que le expliquemos a la computadora qué significa cada cosa +(¡y eso puede ser difícil!), no podrá ver cómo +encajan nuestros datos. + +Usando el poder de las computadoras, podemos administrar y analizar datos de maneras mucho +más efectivas y rápidas, pero para usar ese poder, tenemos que configurar +nuestros datos para que la computadora pueda entenderlo (y +las computadoras son muy literales). + +Por eso es extremadamente importante configurar tablas bien formateadas +desde el principio, incluso antes de comenzar a ingresar datos de su +primer experimento preliminar. La organización de datos es la base de +su proyecto de investigación. Puede hacer que sea más fácil o más difícil trabajar con +sus datos a lo largo de su análisis, por lo que vale la pena pensar en cuándo +está ingresando datos o configurando su experimento. Puedes +configurar las cosas de diferentes maneras en hojas de cálculo, pero algunas de estas +opciones pueden limitar tu capacidad para trabajar con los datos en otros programas +o tener la tuya de- Dentro de 6 meses o tu colaborador trabajará con +los datos. + +**Nota:** los mejores diseños/formatos (así como el software y las +interfaces) para la entrada y el análisis de datos pueden ser diferentes. Es +importante tener esto en cuenta e idealmente automatizar la +conversión de uno a otro. + +### Seguimiento de sus análisis + +Cuando trabajas con hojas de cálculo, durante la limpieza de datos o +análisis, es muy fácil terminar con una hoja de cálculo que se ve muy +diferente de la que tenías al principio. Para poder +reproducir tus análisis o descubrir qué hiciste cuando un revisor o +instructor te pide un análisis diferente, debes + +- cree un nuevo archivo con sus datos limpios o analizados. ¡No modifiques + el conjunto de datos original o nunca sabrás por dónde empezaste! + +- Lleve un registro de los pasos que siguió en su limpieza o análisis. Usted + debe realizar un seguimiento de estos pasos como lo haría con cualquier paso de un experimento. + recomendamos que haga esto en un archivo de texto sin formato almacenado en la misma carpeta + que el archivo de datos. + +Este podría ser un ejemplo de configuración de una hoja de cálculo: + +![](fig/spreadsheet-setup-updated.png) + +Pon estos principios en práctica hoy durante tus ejercicios. + +Si bien el control de versiones está fuera del alcance de este curso, puede consultar la lección +Carpentries en +['Git'](https://swcarpentry.github.io/git-novice/) para aprenda cómo +mantener **control de versiones** sobre sus datos. Vea también este blog +post para un tutorial rápido o +@Perez-Riverol:2016 para un tutorial más orientado a la investigación. caso de uso. + +### Estructurar datos en hojas de cálculo. + +Las reglas fundamentales para el uso de programas de hojas de cálculo para datos: + +1. Coloque todas sus variables en columnas: lo que está midiendo, + como 'peso' o 'temperatura'. +2. Coloque cada observación en su propia fila. +3. No combine varias piezas de información en una celda. A veces + simplemente parece una cosa, pero piensa si esa es la única manera + en la que querrás poder usar u ordenar esos datos. +4. Deje los datos sin procesar, ¡no los cambie! +5. Exporte los datos limpios a un formato basado en texto como CSV + (valores separados por comas). Esto garantiza que cualquiera pueda usar + los datos y es requerido por la mayoría de los repositorios de datos. + +Por ejemplo, tenemos datos de pacientes que visitaron varios +hospitales en Bruselas, Bélgica. Registraron la fecha de la visita, +el hospital, el sexo, el peso y el grupo sanguíneo de los pacientes. + +Si tuviéramos que realizar un seguimiento de los datos como este: + +![](fig/multiple-info.png) + +el problema es que los grupos ABO y Rhesus están en la misma columna de tipo `Blood` +. Entonces, si quisieran ver todas las observaciones del grupo A +o ver las distribuciones de peso por grupo ABO, sería complicado +hacerlo usando esta configuración de datos. Si en cambio ponemos los grupos ABO y Rhesus +en columnas diferentes, puedes ver que sería mucho más fácil. + +![](fig/single-info.png) + +Una regla importante al configurar una hoja de datos es que **las columnas se usan +para las variables** y **las filas se usan para las observaciones**: + +- las columnas son variables +- las filas son observaciones +- las celdas son valores individuales + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: tomaremos un conjunto de datos desordenado y describiremos cómo lo limpiaríamos. + +1. Descargue un conjunto de datos desordenado haciendo clic en + [aquí](https://github.com/UCLouvain-CBIO/WSBIM1207/raw/master/data/messy_covid.xlsx). + +2. Abra los datos en un programa de hoja de cálculo. + +3. Puedes ver que hay dos pestañas. Los datos contienen varias + variables clínicas registradas en varios hospitales de Bruselas durante + la primera y segunda oleada de COVID-19 en 2020. Como puede ver, los datos + se registraron de manera diferente durante las oleadas + de marzo y noviembre. Ahora eres la persona a cargo de este proyecto y quieres que + pueda comenzar a analizar los datos. + +4. Con la persona a tu lado, identifica qué está mal en esta hoja de cálculo + . También analice los pasos que necesitaría seguir para limpiar + las pestañas de la primera y segunda ola, y juntarlas todas en una + hoja de cálculo. + +**Importante:** No olvide nuestro primer consejo: para crear un +nuevo archivo (o pestaña) para los datos limpios, nunca modifique sus datos originales +(sin procesar). + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +Después de realizar este ejercicio, discutiremos en grupo qué +estaba mal con estos datos y cómo solucionarlo. + + + + + + + + + + + + + + + + + + + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: una vez que haya ordenado los datos, responda las siguientes preguntas: + +- ¿Cuántos hombres y mujeres participaron en el estudio? +- ¿Cuántos tipos A, AB y B se han probado? +- ¿Como arriba, pero sin tener en cuenta las muestras contaminadas? +- ¿Cuántos Rhesus + y - se han probado? +- ¿Cuántos donantes universales (O-) se han probado? +- ¿Cuál es el peso promedio de los hombres AB? +- ¿Cuántas muestras se han analizado en los diferentes hospitales? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +Una **excelente referencia**, en particular con respecto a las secuencias de comandos R +es el artículo _Tidy Data_ @Wickham:2014. + +## Errores comunes en las hojas de cálculo + +**Preguntas** + +- ¿Cuáles son algunos de los desafíos comunes al formatear datos en hojas de cálculo + y cómo podemos evitarlos? + +**Objetivos** + +- Reconocer y resolver problemas comunes de formato de hojas de cálculo. + +**Puntos clave** + +- Evite el uso de varias tablas dentro de una hoja de cálculo. +- Evite distribuir datos en varias pestañas. +- Registre los ceros como ceros. +- Utilice un valor nulo apropiado para registrar los datos faltantes. +- No utilices el formato para transmitir información o hacer que tu hoja de cálculo luzca bonita. +- Coloque los comentarios en una columna separada. +- Registre las unidades en los encabezados de las columnas. +- Incluya solo una pieza de información en una celda. +- Evite espacios, números y caracteres especiales en los encabezados de las columnas. +- Evite caracteres especiales en sus datos. +- Registre los metadatos en un archivo de texto sin formato separado. + + + + + + + + + +Hay algunos errores potenciales a los que debe prestar atención en sus propios datos +, así como en los datos de sus colaboradores o de Internet. Si es +consciente de los errores y del posible efecto negativo en el análisis de datos y la interpretación de resultados de +posteriores, podría motivarse a usted mismo +y a los miembros de su proyecto a intentar evitarlos. Hacer pequeños cambios +en la forma en que formatea sus datos en las hojas de cálculo puede tener un gran +impacto en la eficiencia y confiabilidad cuando se trata de limpieza y análisis de datos +. + +- [Usando varias tablas](#tables) +- [Usar varias pestañas](#pestañas) +- [Sin completar ceros](#zeros) +- [Usando valores nulos problemáticos](#null) +- [Usar formato para transmitir información](#formateo) +- [Usar formato para que la hoja de datos se vea bonita](#formatting_pretty) +- [Colocar comentarios o unidades en celdas](#unidades) +- [Ingresar más de un dato en una celda](#info) +- [Usando nombres de campos problemáticos](#field_name) +- [Usar caracteres especiales en los datos](#special) +- [Inclusión de metadatos en tabla de datos](#metadata) + +### Usando múltiples tablas {#tables} + +Una estrategia común es crear varias tablas de datos dentro de una +hoja de cálculo. Esto confunde a la computadora, ¡así que no hagas esto! Cuando +creas varias tablas dentro de una hoja de cálculo, estás dibujando +asociaciones falsas entre cosas para la computadora, que ve cada fila como +una observación. También estás potencialmente usando el mismo nombre de campo en +varios lugares, lo que hará que sea más difícil limpiar tus datos en +un formulario utilizable. El siguiente ejemplo muestra el problema: + +![](fig/2_datasheet_example.jpg) + +En el ejemplo anterior, la computadora verá (por ejemplo) la fila 4 y +asumirá que todas las columnas A-AF se refieren a la misma muestra. Esta fila +en realidad representa cuatro muestras distintas (muestra 1 para cada una de las cuatro +fechas de recolección diferentes: 29 de mayo, 12 de junio, 19 de junio y +26 de junio), así como algunas estadísticas resumidas calculadas (un promedio (avr) +y un error estándar de medición (SEM)) para dos de esas +muestras. Otras filas son igualmente problemáticas. + +### Usando múltiples pestañas {#tabs} + +Pero ¿qué pasa con las pestañas del libro de trabajo? Parece una manera fácil de organizar +datos, ¿verdad? Bueno, sí y no. Cuando crea pestañas adicionales, no +permite que la computadora vea las conexiones en los datos que están allí (usted +tiene que introducir funciones específicas de la aplicación de hoja de cálculo o +secuencias de comandos para garantizar esta conexión). Digamos, por ejemplo, que creas una +pestaña separada para cada día que tomas una medición. + +Esta no es una buena práctica por dos razones: + +1. es más probable que accidentalmente agregue inconsistencias a sus + datos si cada vez que toma una medición, comienza a registrar datos + en una nueva pestaña, y + +2. even if you manage to prevent all inconsistencies from creeping in, + you will add an extra step for yourself before you analyse the data + because you will have to combine these data into a single + datatable. Tendrás que decirle explícitamente a la computadora cómo + combinar pestañas, y si las pestañas tienen un formato inconsistente, es posible que + incluso tengas que hacerlo manualmente. + +La próxima vez que ingrese datos y vaya a crear otra pestaña +o tabla, pregúntese si podría evitar agregar esta pestaña agregando +otra columna a su hoja de cálculo original. Usamos varias pestañas en +nuestro ejemplo de un archivo de datos desordenado, pero ahora has visto cómo puedes +reorganizar tus datos para consolidarlos entre pestañas. + +Su hoja de datos puede volverse muy larga durante el transcurso del experimento +. Esto hace que sea más difícil ingresar datos si no puedes ver los encabezados +en la parte superior de la hoja de cálculo. Pero no repita la fila del encabezado +. Estos pueden mezclarse fácilmente con los datos, generando problemas +en el futuro. En su lugar, puede [congelar los encabezados de la columna +](https://support.office.com/en-ca/article/Freeze-column-headings-for-easy-scrolling-57ccce0c-cf85-4725-9579 -c5d13106ca6a) +para que permanezcan visibles incluso cuando tengas una hoja de cálculo con muchas +filas. + +### No completar ceros {#zeros} + +Puede ser que cuando estás midiendo algo, generalmente sea un cero, +dice la cantidad de veces que se observa un conejo en la encuesta. ¿Por qué molestarse +en escribir el número cero en esa columna, cuando en su mayoría son ceros? + +Sin embargo, existe una diferencia entre un cero y una celda en blanco en una hoja de cálculo +. Para la computadora, un cero son en realidad datos. Lo mediste o +lo contaste. Una celda en blanco significa que no se midió y la computadora +la interpretará como un valor desconocido (también conocido como nulo +o valor faltante). + +Es probable que las hojas de cálculo o los programas estadísticos malinterpreten +celdas en blanco que usted pretende que sean ceros. Al no ingresar el valor de +su observación, le está diciendo a su computadora que represente esos datos +como desconocidos o faltantes (nulos). Esto puede causar problemas con +cálculos o análisis posteriores. Por ejemplo, el promedio de un conjunto de números +que incluye un único valor nulo siempre es nulo (porque la computadora +no puede adivinar el valor de las observaciones faltantes). Debido a +esto, es muy importante registrar los ceros como ceros y realmente +los datos faltantes como nulos. + +### Usar valores nulos problemáticos {#null} + +**Ejemplo**: usar -999 u otros valores numéricos (o cero) para +representar datos faltantes. + +**Soluciones**: + +Hay algunas razones por las que los valores nulos se representan de manera diferente +dentro de un conjunto de datos. A veces, los valores nulos confusos se registran automáticamente +desde el dispositivo de medición. Si ese es el caso, no hay +mucho que puedas hacer, pero se puede abordar en la limpieza de datos con una herramienta +como +[OpenRefine](https://www.datacarpentry .org/OpenRefine-ecology-lesson/) +antes del análisis. Otras veces se utilizan diferentes valores nulos para transmitir +diferentes razones por las que los datos no están ahí. Esta es +información importante para capturar, pero en realidad se utiliza una columna para capturar +dos piezas de información. Like for using formatting to convey +information it would be good here to create a new +column like 'data\_missing' and use that column to capture the +different reasons. + +Cualquiera sea el motivo, es un problema si datos desconocidos o faltantes se registran +como -999, 999 o 0. + +Muchos programas estadísticos no reconocerán que estos +pretenden representar valores faltantes (nulos). La forma en que se interpreten estos valores +dependerá del software que utilice para analizar sus datos. Es +esencial utilizar un indicador nulo claramente definido y consistente. + +Los espacios en blanco (la mayoría de las aplicaciones) y NA (para R) son buenas opciones +. @White:2013 explica buenas opciones para indicar valores nulos +para diferentes aplicaciones de software en su artículo: + +![](fig/3_white_table_1.jpg) + +### Usar formato para transmitir información {#formatting} + +**Ejemplo**: resaltar celdas, filas o columnas que deben excluirse +de un análisis, dejando filas en blanco para indicar +separaciones en los datos. + +![](fig/formateo.png) + +**Solución**: cree un nuevo campo para codificar qué datos deben excluirse +. + +![](fig/good_formatting.png) + +### Usar formato para que la hoja de datos se vea bonita {#formatting\_pretty} + +**Ejemplo**: fusionar celdas. + +**Solución**: Si no tiene cuidado, formatear una hoja de cálculo para que sea más +estéticamente agradable puede comprometer la capacidad de su computadora para ver +asociaciones en los datos. Las celdas combinadas harán que sus datos sean ilegibles +para el software de estadísticas. Considere reestructurar sus datos de tal manera +que no necesite fusionar celdas para organizar sus datos. + +### Colocar comentarios o unidades en celdas {#units} + +La mayoría del software de análisis no puede ver los comentarios de Excel o LibreOffice, y +se confundiría con los comentarios colocados dentro de sus celdas de datos. Como +se describió anteriormente para el formato, cree otro campo si necesita +agregar notas a las celdas. De manera similar, no incluyas unidades en las celdas: idealmente, +todas las medidas que coloques en una columna deberían estar en la misma +unidad, pero si por alguna razón no lo están, crea otro campo y +especifican las unidades en las que se encuentra la celda. + +### Ingresar más de un dato en una celda {#info} + +**Ejemplo**: Grabar grupos ABO y Rhesus en una celda, como A+, +B+, A-, ... + +**Solución**: No incluyas más de un dato en una celda +. Esto limitará las formas en que puede analizar sus datos. Si +necesita ambas medidas, diseñe su hoja de datos para incluir +esta información. Por ejemplo, incluya una columna para el grupo ABO y +una para el grupo Rhesus. + +### Usar nombres de campos problemáticos {#field\_name} + +Elija nombres de campos descriptivos, pero tenga cuidado de no incluir espacios, números +ni caracteres especiales de ningún tipo. Los espacios pueden ser +mal interpretados por analizadores que usan espacios en blanco como delimitadores y a algunos programas +no les gustan los nombres de campos que son cadenas de texto que comienzan con +números. + +Los guiones bajos (`_`) son una buena alternativa a los espacios. Considere escribir +nombres en mayúsculas y minúsculas (como este: Ejemplo de nombre de archivo) para mejorar la legibilidad de +. Recuerda que las abreviaturas que tienen sentido en este momento +pueden no ser tan obvias en 6 meses, pero no te excedas con nombres que +son excesivamente largos. Incluir las unidades en los nombres de los campos evita +confusión y permite que otros interpreten fácilmente sus campos. + +**Ejemplos** + +| Buen nombre | Buena alternativa | Evitar | +| -------------------------------------------------------- | ------------------------------------------ | ------------------------------------------ | +| Máx\_temp\_C | Temperatura máxima | Temperatura máxima (°C) | +| Precipitación\_mm | Precipitación | precm | +| Crecimiento medio\_año\_ | Crecimiento medio anual | Crecimiento medio/año | +| sexo | sexo | L/F | +| peso | peso | w. | +| tipo de célula | Tipo de célula | Tipo de célula | +| Observación\_01 | primera\_observación | 1.ª observación | + +### Usar caracteres especiales en datos {#special} + +**Ejemplo**: Tratas tu programa de hoja de cálculo como un procesador de textos +cuando escribes notas, por ejemplo, copiando datos directamente desde Word u +otras aplicaciones. + +**Solución**: Esta es una estrategia común. Por ejemplo, al escribir +texto más largo en una celda, las personas suelen incluir saltos de línea, guiones, +, etc. en su hoja de cálculo. Además, al copiar datos desde +aplicaciones como Word, se incluyen +formatos y caracteres elegantes no estándar +(como comillas alineadas a la izquierda y a la derecha). Al exportar estos datos a un entorno de codificación/estadístico +o a una base de datos relacional, pueden ocurrir cosas peligrosas, +, como líneas cortadas por la mitad y errores de codificación. + +La mejor práctica general es evitar agregar caracteres como nuevas líneas, pestañas +y pestañas verticales. En otras palabras, trate una celda de texto como si +fuera un formulario web simple que solo puede contener texto y espacios. + +### Inclusión de metadatos en tabla de datos {#metadata} + +**Ejemplo**: Agrega una leyenda en la parte superior o inferior de su tabla de datos +explicando el significado de las columnas, las unidades, las excepciones, etc. + +**Solución**: Registrar datos sobre sus datos ("metadatos") es +esencial. You may be on intimate terms with your dataset while you +are collecting and analysing it, but the chances that you will still +remember that the variable "sglmemgp" means single member of group, +for example, or the exact algorithm you used to transform a variable +or create a derived one, after a few months, a year, or more are slim. + +Además, hay muchas razones por las que otras personas pueden querer examinar o +usar sus datos: para comprender sus hallazgos, para verificar sus hallazgos, +para revisar la publicación enviada, para replicar sus resultados, para +diseñar un estudio similar, o incluso archivar sus datos para que otros puedan acceder a ellos y +reutilizarlos. Si bien los datos digitales, por definición, son +legibles por máquina, comprender su significado es una tarea para los seres humanos +. No se puede sobrestimar la importancia de documentar sus datos durante la fase de recopilación +y análisis de su investigación, +, especialmente si su investigación va a ser parte del registro académico +. + +Sin embargo, los metadatos no deben estar contenidos en el propio archivo de datos +. A diferencia de una tabla en un documento o un archivo complementario, los metadatos (en +la forma de leyendas) no deben incluirse en un archivo de datos ya que esta información +no son datos, y su inclusión puede alterar la forma Los programas +de computadora interpretan su archivo de datos. Más bien, los metadatos deben almacenarse +como un archivo separado en el mismo directorio que su archivo de datos, preferiblemente +en formato de texto sin formato con un nombre que lo asocie claramente con su archivo de datos +. . Because metadata files are free text format, they also +allow you to encode comments, units, information about how null values +are encoded, etc. that are important to document but can disrupt the +formatting of your data file. + +Además, los metadatos a nivel de archivo o base de datos describen cómo los archivos que +componen el conjunto de datos se relacionan entre sí; en qué formato están; y +si reemplazan o son reemplazados por archivos anteriores. Un archivo readme.txt a nivel de carpeta +es la forma clásica de contabilizar todos +los archivos y carpetas de un proyecto. + +(Texto sobre metadatos adaptado del curso en línea Research Data +[MANTRA](https://datalib.edina.ac.uk/mantra) de EDINA y Data Library, +Universidad de Edimburgo. MANTRA tiene una licencia Creative Commons +Attribution 4.0 International +.) + +## Exportar datos + +**Pregunta** + +- ¿Cómo podemos exportar datos de hojas de cálculo de una manera que sea útil para + aplicaciones posteriores? + +**Objetivos** + +- Almacene datos de hojas de cálculo en formatos de archivo universales. +- Exporte datos de una hoja de cálculo a un archivo CSV. + +**Puntos clave** + +- Los datos almacenados en formatos comunes de hojas de cálculo a menudo no se leerán + correctamente en el software de análisis de datos, lo que introducirá errores en sus datos + . + +- Exportar datos de hojas de cálculo a formatos como CSV o TSV los coloca + en un formato que la mayoría de los programas pueden usar de manera consistente. + +Almacenar los datos con los que va a trabajar para sus análisis en el formato de archivo predeterminado de Excel +(`*.xls` o `*.xlsx`, dependiendo de la versión de Excel +) no es una buena idea. ¿Por qué? + +- Debido a que es un formato propietario, y es posible que en el + futuro, la tecnología no exista (o se vuelva lo suficientemente rara) como para + hacer que sea inconveniente, si no imposible, abrir el formato. archivo. + +- Es posible que otro software de hoja de cálculo no pueda abrir archivos guardados en un formato propietario de Excel + . + +- Las diferentes versiones de Excel pueden manejar los datos de manera diferente, lo que genera + inconsistencias. [Fechas](https://datacarpentry.org/spreadsheet-ecology-lesson/03-dates-as-data/index.html) + es un ejemplo bien documentado de inconsistencias en el almacenamiento de datos. + +- Finalmente, más revistas y agencias de subvenciones exigen que + deposite sus datos en un repositorio de datos, y la mayoría de ellos no + aceptan el formato Excel. Debe estar en uno de los formatos que se analizan + a continuación. + +- Los puntos anteriores también se aplican a otros formatos, como los formatos de datos abiertos + utilizados por LibreOffice/Open Office. Estos formatos no son + estáticos y no se analizan de la misma manera por diferentes paquetes de software + . + +Almacenar datos en un formato universal, abierto y estático ayudará a solucionar +este problema. Pruebe delimitado por tabulaciones (valores separados por tabulaciones o TSV) o +delimitado por comas (valores separados por comas o CSV). Los archivos CSV son archivos de texto simple +donde las columnas están separadas por comas, de ahí 'valores separados por coma +' o CSV. La ventaja de un archivo CSV sobre un +Excel/SPSS/etc. El archivo es que podemos abrir y leer un archivo CSV usando +casi cualquier software, incluidos editores de texto sin formato como TextEdit o +NotePad. Los datos en un archivo CSV también se pueden importar fácilmente a otros +formatos y entornos, como SQLite y R. No estamos atados a una +determinada versión de un determinado programa costoso cuando trabajamos con Archivos CSV +, por lo que es un buen formato para trabajar para máxima portabilidad y +resistencia. La mayoría de los programas de hojas de cálculo pueden guardar fácilmente en formatos de texto delimitado +como CSV, aunque pueden darte una advertencia durante +la exportación del archivo. + +Para guardar un archivo que ha abierto en Excel en formato CSV: + +1. En el menú superior, seleccione "Archivo" y "Guardar como". +2. En el campo 'Formato', de la lista, seleccione 'Valores + separados por comas' (`*.csv`). +3. Verifique dos veces el nombre del archivo y la ubicación donde desea guardarlo + y presione 'Guardar'. + +Una nota importante para la compatibilidad con versiones anteriores: ¡puedes abrir archivos CSV +en Excel! + +```{r, results="markup", fig.cap="Saving an Excel file to CSV.", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/excel-to-csv.png") +``` + +**Una nota sobre R y `xls`**: Hay paquetes de R que pueden leer archivos `xls` +(así como hojas de cálculo de Google). Incluso es posible acceder a +diferentes hojas de trabajo en los documentos `xls`. + +**Pero** + +- algunos de estos sólo funcionan en Windows. +- esto equivale a reemplazar una exportación (simple pero manual) a `csv` con + complejidad/dependencias adicionales en el código R de análisis de datos. +- Las mejores prácticas de formato de datos aún se aplican. +- ¿Existe realmente una buena razón por la cual `csv` (o similar) no es + adecuado? + +### Advertencias sobre las comas + +En algunos conjuntos de datos, los propios valores de los datos pueden incluir comas +(,). En ese caso, lo más probable es que el software que utilice (incluido Excel) +muestre incorrectamente los datos en columnas. Esto se debe a que +las comas que forman parte de los valores de datos se interpretarán como +delimitadores. + +Por ejemplo, nuestros datos podrían verse así: + +``` +species_id,genus,species,taxa +AB,Amphispiza,bilineata,Bird +AH,Ammospermophilus,harrisi,Rodent, not censused +AS,Ammodramus,savannarum,Bird +BA,Baiomys,taylori,Rodent +``` + +En el registro `AH,Ammospermophilus,harrisi,Roedor, no censado` el valor +para `taxa` incluye una coma (`Roedor, no censado`). Si intentamos +leer lo anterior en Excel (u otro programa de hoja de cálculo), +obtendremos algo como esto: + +```{r, results="markup", fig.cap="The risks of having commas inside comma-separated data.", echo=FALSE, purl=FALSE, out.width="80%", fig.align="center"} +knitr::include_graphics("fig/csv-mistake.png") +``` + +El valor de `taxa` se dividió en dos columnas (en lugar de colocarse +en una columna `D`). Esto puede propagarse a una serie de errores +adicionales. Por ejemplo, la columna adicional se interpretará como una columna +con muchos valores faltantes (y sin un encabezado adecuado). Además de +eso, el valor en la columna `D` para el registro en la fila 3 (por lo tanto, el +donde el valor de 'taxa' contenía la coma) ahora es incorrecto. + +Si desea almacenar sus datos en formato `csv` y espera que sus valores de datos +puedan contener comas, puede evitar el problema discutido +anteriormente poniendo los valores entre comillas (""). Aplicando esta regla, nuestros datos +podrían verse así: + +``` +spec_id,género,especie,taxones +"AB","Amphispiza","bilineata","Bird" +"AH","Ammospermophilus","harrisi","Roedor, no censado" +"AS","Ammodramus","savannarum","Pájaro" +"BA","Baiomys","taylori","Roedor" +``` + +Ahora, abrir este archivo como `csv` en Excel no generará una columna +adicional, porque Excel solo usará comas que queden fuera de las comillas +como caracteres delimitadores. + +Alternativamente, si está trabajando con datos que contienen comas, +probablemente necesitará usar otro delimitador cuando trabaje en una hoja de cálculo +[^decsep]. En este caso, considere usar pestañas como delimitador y +trabajar con archivos TSV. Los archivos TSV se pueden exportar desde programas de hoja de cálculo +de la misma manera que los archivos CSV. + +[^decsep]: Esto es particularmente relevante en los países europeos + donde la coma se usa como separador decimal + . En tales casos, el separador de valores predeterminado en un archivo csv + será el punto y coma (;), o los valores se citarán + sistemáticamente. + +Si está trabajando con un conjunto de datos ya existente en el que los valores de datos +no están incluidos en "" pero que tienen comas como delimitadores +y partes de los valores de datos, potencialmente se enfrenta a un problema importante. +con limpieza de datos. Si el conjunto de datos con el que está tratando contiene +cientos o miles de registros, límpielos manualmente (ya sea +eliminando comas de los valores de datos o poniendo los valores entre +comillas - "") no solo llevará horas y horas, sino que +potencialmente terminará introduciendo accidentalmente muchos errores. + +La limpieza de conjuntos de datos es uno de los principales problemas en muchas disciplinas científicas +. El enfoque casi siempre depende del contexto +particular. Sin embargo, es una buena práctica limpiar los datos de forma +automatizada, por ejemplo escribiendo y ejecutando un script. Las +lecciones de Python y R le brindarán la base para desarrollar habilidades para +crear scripts relevantes. + +## Resumen + +```{r analysis, results="asis", fig.margin=TRUE, fig.cap="A typical data analysis workflow.", fig.width=7, fig.height=4, echo=FALSE, purl=FALSE} +knitr::include_graphics("fig/analysis.png") +``` + +En la figura anterior, +, se ilustra un flujo de trabajo de análisis de datos típico, donde los datos se transforman, visualizan y modelan repetidamente. Esta iteración +se repite varias veces hasta que se comprenden los datos. Sin embargo, en +muchos casos de la vida real, la mayor parte del tiempo se dedica a limpiar y +preparar los datos, en lugar de analizarlos y comprenderlos +. + +An agile data analysis workflow, with several fast iterations of the +transform/visualise/model cycle is only feasible if the data is +formatted in a predictable way and one can reason about the data +without having to look at it and/or fix it. + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Una buena organización de los datos es la base de cualquier proyecto de investigación. + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/es/episodes/20-r-rstudio.Rmd b/locale/es/episodes/20-r-rstudio.Rmd new file mode 100644 index 000000000..13d517ad9 --- /dev/null +++ b/locale/es/episodes/20-r-rstudio.Rmd @@ -0,0 +1,668 @@ +--- +source: Rmd +title: R y RStudio +teaching: 30 +exercises: 0 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Describa el propósito de los paneles RStudio Script, Consola, Entorno y Gráficos. +- Organice archivos y directorios para un conjunto de análisis como un proyecto de R y comprenda el propósito del directorio de trabajo. +- Utilice la interfaz de ayuda integrada de RStudio para buscar más información sobre las funciones de R. +- Demuestre cómo proporcionar suficiente información para la resolución de problemas con la comunidad de usuarios de R. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- ¿Qué son R y RStudio? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +> Este episodio se basa en la lección _Análisis de datos y +> Visualización en R para ecologistas_ de Data Carpentries. + +## ¿Qué es R? ¿Qué es RStudio? + +El término [R](https://www.r-project.org/) se utiliza para referirse al +_lenguaje de programación_, el _entorno para la computación estadística_ +y _el software_ que interpreta los scripts escritos con él. + +[RStudio](https://rstudio.com) es actualmente una forma muy popular de +no sólo escribir tus scripts R sino también de interactuar con el software R +[^plainr]. Para funcionar correctamente, RStudio necesita R y +, por lo que ambos deben estar instalados en su computadora. + +[^plainr]: A diferencia de usar R directamente desde la línea de comando + consola. Existe otro software que interactúa e integra + con R, pero RStudio es particularmente adecuado para principiantes + y al mismo tiempo proporciona numerosas funciones muy avanzadas. + +La Hoja de trucos de RStudio IDE + +proporciona mucha más información de la que se cubrirá aquí. pero puede ser +útil para aprender atajos de teclado y descubrir nuevas funciones. + +## ¿Por qué aprender R? + +### R no implica mucho apuntar y hacer clic, y eso es bueno + +The learning curve might be steeper than with other software, but with +R, the results of your analysis do not rely on remembering a +succession of pointing and clicking, but instead on a series of +written commands, and that's a good thing! Por lo tanto, si desea rehacer +su análisis porque recopiló más datos, no tiene que +recordar en qué botón hizo clic y en qué orden para obtener sus +resultados; solo tienes que ejecutar tu script nuevamente. + +Trabajar con scripts aclara los pasos que utilizó en su análisis, +y el código que escribe puede ser inspeccionado por otra persona que puede brindarle +comentarios y detectar errores. + +Trabajar con scripts te obliga a tener una comprensión más profunda de lo +que estás haciendo y facilita tu aprendizaje y comprensión de los +métodos que utilizas. + +### El código R es excelente para la reproducibilidad + +Reproducibilidad significa que otra persona (incluido su yo futuro) puede +obtener los mismos resultados del mismo conjunto de datos cuando usa el mismo código de análisis +. + +R se integra con otras herramientas para generar manuscritos o informes a partir de su código +. Si recopila más datos o corrige un error en su conjunto de datos, las +cifras y las pruebas estadísticas de su manuscrito o informe se actualizan +automáticamente. + +Un número cada vez mayor de revistas y agencias de financiación esperan que los análisis +sean reproducibles, por lo que conocer R le dará una ventaja con estos requisitos de +. + +### R es interdisciplinario y extensible. + +Con más de 10000 paquetes[^whatarepkgs] que se pueden instalar para ampliar sus +capacidades, R proporciona un marco que le permite combinar +enfoques estadísticos de muchas disciplinas científicas para adaptarse mejor a +el marco analítico que necesita para analizar sus datos. Por ejemplo, +R tiene paquetes para análisis de imágenes, SIG, series temporales, genética de poblaciones +y mucho más. + +[^whatarepkgs]: es decir, complementos que confieren a R nuevas funciones, + , como el análisis de datos bioinformáticos. + +```{r, fig.cap="Exponential increase of the number of packages available on [CRAN](https://cran.r-project.org/), the Comprehensive R Archive Network. From the R Journal, Volume 10/2, December 2018.", echo=FALSE, message=FALSE} +knitr::include_graphics("fig/cran.png") +``` + +### R trabaja con datos de todas las formas y tamaños + +Las habilidades que aprende con R se escalan fácilmente con el tamaño de su conjunto de datos +. Ya sea que su conjunto de datos tenga cientos o millones de líneas, +no hará mucha diferencia para usted. + +R está diseñado para el análisis de datos. Viene con estructuras de datos especiales +y tipos de datos que hacen conveniente el manejo de datos faltantes y factores estadísticos +. + +R puede conectarse a hojas de cálculo, bases de datos y muchos otros formatos de datos, +en su computadora o en la web. + +### R produce gráficos de alta calidad + +Las funcionalidades de trazado en R son extensas y le permiten ajustar +cualquier aspecto de su gráfico para transmitir de manera más efectiva el mensaje de +sus datos. + +### R tiene una comunidad grande y acogedora + +Miles de personas utilizan R a diario. Muchos de ellos están dispuestos a ayudarte +a través de listas de correo y sitios web como Stack +Overflow, o en RStudio +comunidad. Estas amplias comunidades de usuarios +se extienden a áreas especializadas como la bioinformática. Uno de esos subconjuntos de la comunidad R es [Bioconductor](https://bioconductor.org/), un proyecto científico para el análisis y la comprensión "de datos de ensayos biológicos actuales y emergentes". Este taller fue desarrollado por miembros de la comunidad Bioconductor; Para obtener más información sobre Bioconductor, consulte el taller complementario ["The Bioconductor Project"](https://carpentries-incubator.github.io/bioc-project/). + +### R no sólo es gratuito, sino que también es de código abierto y multiplataforma + +Cualquiera puede inspeccionar el código fuente para ver cómo funciona R. Debido a esta +transparencia, hay menos posibilidades de cometer errores, y si usted (o +otra persona) encuentra algunos, puede informar y corregir errores. + +## Conociendo RStudio + +Comencemos aprendiendo sobre [RStudio](https://www.rstudio.com/), +, que es un entorno de desarrollo integrado (IDE) para trabajar con +R. + +El producto de código abierto RStudio IDE es gratuito bajo la [Licencia pública Affero General +(AGPL) v3] (https://www.gnu.org/licenses/agpl-3.0.en.html). +El IDE de RStudio también está disponible con una licencia comercial y +soporte prioritario por correo electrónico de Posit, Inc. + +Usaremos el IDE de RStudio para escribir código, navegar por los archivos en nuestra +computadora, inspeccionar las variables que vamos a crear y visualizar +los gráficos que generaremos. RStudio también se puede utilizar para otras cosas +(por ejemplo, control de versiones, desarrollo de paquetes, escritura de aplicaciones Shiny) que +no cubriremos durante el taller. + +```{r, results="markup", fig.cap="RStudio interface screenshot. Clockwise from top left: Source, Environment/History, Files/Plots/Packages/Help/Viewer, Console.", echo=FALSE, purl=FALSE, out.width="100%", fig.align="center"} +knitr::include_graphics("fig/rstudio-screenshot.png") +``` + +La ventana de RStudio está dividida en 4 "Paneles": + +- la **Fuente** de tus guiones y documentos (arriba a la izquierda, en el diseño predeterminado + ) +- su **Entorno/Historia** (arriba a la derecha), +- sus **Archivos/Tramas/Paquetes/Ayuda/Visor** (abajo a la derecha), y +- la **Consola** R (abajo a la izquierda). + +La ubicación de estos paneles y su contenido se pueden personalizar (consulte el menú +, `Herramientas -> Opciones globales -> Diseño del panel`). + +Una de las ventajas de usar RStudio es que toda la información que +necesitas para escribir código está disponible en una sola ventana. Además, con +muchos atajos, **autocompletado** y **resaltado** para los principales tipos de archivos +que utiliza mientras desarrolla en R, RStudio hará que escribir +sea más fácil. y menos propenso a errores. + +## Preparándose + +Es una buena práctica mantener un conjunto de datos, análisis y texto relacionados +independientes en una sola carpeta, llamada \*\*directorio de trabajo +\*\*. Todos los scripts dentro de esta carpeta pueden usar +**rutas relativas** a archivos que indican dónde dentro del proyecto se encuentra un archivo +(a diferencia de rutas absolutas, que apuntan a donde se encuentra un archivo +). +archivo está en una computadora específica). Trabajar de esta manera hace que sea mucho +más fácil mover su proyecto en su computadora y compartirlo con +otras personas sin preocuparse de si los scripts subyacentes +seguirán funcionando o no. + +RStudio proporciona un útil conjunto de herramientas para hacer esto a través de su interfaz "Proyectos" +, que no solo crea un directorio de trabajo para usted, sino que también recuerda +su ubicación (lo que le permite navegar rápidamente hasta él). ) y, opcionalmente, conserva +configuraciones personalizadas y archivos abiertos para que sea más fácil reanudar el trabajo después de un descanso de +. Siga los pasos para crear un "Proyecto R" para este +tutorial a continuación. + +1. Inicie RStudio. +2. En el menú "Archivo", haga clic en "Nuevo proyecto". Elija `Nuevo directorio`, luego + `Nuevo proyecto`. +3. Ingrese un nombre para esta nueva carpeta (o "directorio") y elija una + ubicación conveniente para ella. Este será su **directorio de trabajo** + para esta sesión (o el curso completo) (por ejemplo, `bioc-intro`). +4. Haga clic en `Crear proyecto`. +5. (Opcional) Establezca las Preferencias en "Nunca" guardar el espacio de trabajo en RStudio. + +Las preferencias predeterminadas de RStudio generalmente funcionan bien, pero guardar un espacio de trabajo en +.RData puede ser engorroso, especialmente si trabaja con conjuntos de datos más grandes. +Para desactivarlo, vaya a Herramientas --> 'Opciones globales' y seleccione la opción 'Nunca' +para 'Guardar espacio de trabajo en .RData' al salir. + +```{r, results="markup", fig.cap="Set 'Save workspace to .RData on exit' to 'Never'", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/rstudio-preferences.png") +``` + +Para evitar problemas de codificación de caracteres entre Windows y otros sistemas operativos +, vamos +a configure UTF-8 de forma predeterminada: + +```{r, results="markup", fig.cap="Set the default text encoding to UTF-8 to save us headache in the coming future. (Figure from the link above).", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/utf8.png") +``` + +### Organizando su directorio de trabajo + +Usar una estructura de carpetas coherente en todos tus proyectos te ayudará a mantener las cosas +organizadas y también facilitará la búsqueda y el archivo de cosas en el futuro. Este +puede resultar especialmente útil cuando tienes varios proyectos. En general, puedes +crear directorios (carpetas) para **scripts**, **datos** y **documentos**. + +- **`data/`** Utilice esta carpeta para almacenar sus datos sin procesar y conjuntos de datos + intermedios que pueda crear para la necesidad de un análisis particular. Por + en aras de la transparencia y + [procedencia](https://en.wikipedia.org/wiki/Provenance), debes + _siempre_ guardar una copia de tu datos sin procesar accesibles y haga la mayor cantidad de + limpieza y preprocesamiento de sus datos mediante programación (es decir, con + scripts, en lugar de manualmente) como sea posible. También es una buena idea separar los datos sin procesar + de los datos procesados. Por ejemplo, podría + tener los archivos `data/raw/tree_survey.plot1.txt` y `...plot2.txt` mantenidos + separados de `data/processed/tree.survey. csv` generado por + el script `scripts/01.preprocess.tree_survey.R`. +- **`documents/`** Este sería un lugar para guardar esquemas, borradores, + y otro texto. +- **`scripts/`** (o `src`) Esta sería la ubicación para guardar tus scripts R + para diferentes análisis o trazados, y potencialmente una carpeta + separada para tus funciones (más sobre eso más adelante). + +Es posible que desee directorios o subdirectorios adicionales dependiendo de +las necesidades de su proyecto, pero estos deberían formar la columna vertebral de su directorio de trabajo +. + +```{r, results="markup", fig.cap="Example of a working directory structure.", echo=FALSE, purl=FALSE, out.width="100%", fig.align="center"} +knitr::include_graphics("fig/working-directory-structure.png") +``` + +Para este curso, necesitaremos una carpeta `data/` para almacenar nuestros datos sin procesar, +y usaremos `data_output/` cuando aprendamos a exportar datos como +archivos CSV, y Carpeta `fig_output/` para las figuras que guardaremos. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: crea la estructura de directorios de tu proyecto + +En la pestaña `Archivos` a la derecha de la pantalla, haga clic en `Nueva carpeta` y +cree una carpeta llamada `data` dentro de su directorio de trabajo recién creado +(por ejemplo, `~/bioc -introducción/datos`). (Como alternativa, escriba `dir.create("data")` en +su consola R). Repita estas operaciones para crear una carpeta `data_output/` y +`fig_output`. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +Mantendremos el script en la raíz de nuestro directorio de trabajo +porque solo usaremos un archivo y facilitará las cosas +. + +Su directorio de trabajo ahora debería verse así: + +```{r, results="markup", fig.cap="How it should look like at the beginning of this lesson", echo=FALSE, purl=FALSE, out.width="100%", fig.align="center"} +knitr::include_graphics("fig/r-starting-how-it-should-look-like.png") +``` + +**La gestión de proyectos** también es aplicable a proyectos de bioinformática, +por supuesto[^bioindatascience]. William Noble (@Noble:2009) propone la +siguiente estructura de directorios: + +[^bioindatascience]: En este curso, consideramos la bioinformática como + ciencia de datos aplicada a datos biológicos o biomédicos. + +> Los nombres de los directorios están en tipo de letra grande y los nombres de archivos están en tipo de letra +> más pequeño. Aquí solo se muestra un subconjunto de los archivos. Tenga en cuenta que las fechas +> tienen el formato `--` para que puedan ordenarse +> en orden cronológico. El código fuente `src/ms-analysis.c` +> se compila para crear `bin/ms-analysis` y está documentado en +> `doc/ms-analysis.html`. Los archivos `README` en los directorios de datos +> especifican quién descargó los archivos de datos de qué URL en qué fecha +> . El script del controlador `results/2009-01-15/runall` genera automáticamente +> los tres subdirectorios split1, split2 y split3, +> correspondientes a tres divisiones de validación cruzada. El script +> `bin/parse-sqt.py` es llamado por ambos scripts del controlador `runall` +> . + +```{r bioinfoproj, fig.cap="Directory structure for a sample bioinformatics project.", out.width="100%", echo=FALSE} +knitr::include_graphics("fig/noble-bioinfo-project.png") +``` + +El aspecto más importante de un directorio de proyecto +bien definido y bien documentado es permitir que alguien que no esté familiarizado con el proyecto +[^futureself] pueda + +1. comprender de qué se trata el proyecto, qué datos están disponibles, qué + análisis se realizaron y qué resultados se produjeron y, lo más importante + +2. repita el análisis nuevamente, con nuevos datos o cambiando algunos + parámetros de análisis. + +[^futureself]: Ese alguien podría ser, y muy probablemente será tu + yo futuro, un par de meses o años después de que se realizaron + los análisis. + +### El directorio de trabajo + +El directorio de trabajo es un concepto importante que hay que comprender. Es el +lugar desde donde R buscará y guardará los archivos. Cuando +escribe código para su proyecto, debe hacer referencia a archivos en relación con +la raíz de su directorio de trabajo y solo necesita archivos dentro de esta estructura +. + +El uso de proyectos de RStudio hace que esto sea fácil y garantiza que su directorio de trabajo +esté configurado correctamente. Si necesita verificarlo, puede usar +`getwd()`. If for some reason your working directory is not what it +should be, you can change it in the RStudio interface by navigating in +the file browser where your working directory should be, and clicking +on the blue gear icon `More`, and select `Set As Working Directory`. +Alternativamente, puede usar `setwd("/path/to/working/directory")` para +restablecer su directorio de trabajo. Sin embargo, sus scripts no deben incluir +esta línea porque fallará en la computadora de otra persona. + +**Ejemplo** + +El siguiente esquema representa el directorio de trabajo `bioc-intro` con los subdirectorios +`data` y `fig_output`, y 2 archivos en este último: + +``` +bioc-intro/data/ + /fig_output/fig1.pdf + /fig_output/fig2.png +``` + +Si estuviéramos en el directorio de trabajo, podríamos referirnos al archivo `fig1.pdf` +usando la ruta relativa `bioc-intro/fig_output/fig1.pdf` o la ruta absoluta +`/ inicio/usuario/bioc-intro/fig_output/fig1.pdf`. + +Si estuviéramos en el directorio `data`, usaríamos la ruta relativa +`../fig_output/fig1.pdf` o la misma ruta absoluta +`/home/user/bioc-intro /fig_output/fig1.pdf`. + +## Interactuando con R + +La base de la programación es que escribimos instrucciones para que las siga la computadora +, y luego le decimos a la computadora que siga esas instrucciones +. Escribimos, o _codificamos_, instrucciones en R porque es un +lenguaje común que tanto la computadora como nosotros podemos entender. Llamamos +a las instrucciones _comandos_ y le decimos a la computadora que siga las instrucciones +_ejecutando_ (también llamado _ejecutando_) esos comandos. + +Hay dos formas principales de interactuar con R: usando la +**consola** o usando **scripts** (archivos de texto sin formato que contienen +su código). El panel de la consola (en RStudio, el panel inferior izquierdo) es +el lugar donde los comandos escritos en lenguaje R se pueden escribir y +ejecutar inmediatamente en la computadora. También es donde se mostrarán los resultados +de los comandos que se han ejecutado. Puede escribir +comandos directamente en la consola y presionar `Enter` para ejecutar esos comandos +, pero se olvidarán cuando cierre la sesión. + +Como queremos que nuestro código y flujo de trabajo sean reproducibles, es mejor +escribir los comandos que queremos en el editor de scripts y guardar el script +. De esta manera, hay un registro completo de lo que hicimos, y +cualquiera (¡incluido nuestro yo futuro!) pueden replicar fácilmente los +resultados en su computadora. Sin embargo, tenga en cuenta que simplemente escribir los comandos +en el script no los _ejecuta_ automáticamente; aún deben enviarse +a la consola para su ejecución. + +RStudio le permite ejecutar comandos directamente desde el editor de scripts +usando el acceso directo `Ctrl` + `Enter` (en Mac, `Cmd` + `Return` también funcionará +). El comando en la línea actual en el script (indicado +por el cursor) o todos los comandos en el texto actualmente seleccionado +se enviarán a la consola y se ejecutarán cuando presione `Ctrl` + +`Entrar`. Puede encontrar otros atajos de teclado en esta [RStudio +hoja de referencia sobre RStudio +IDE] (https://raw.githubusercontent.com/rstudio/cheatsheets/main/rstudio-ide.pdf). + +En algún momento de su análisis, es posible que desee verificar el contenido de una variable +o la estructura de un objeto, sin necesariamente mantener un registro +del mismo en su secuencia de comandos. Puede escribir estos comandos y ejecutarlos +directamente en la consola. RStudio proporciona los atajos `Ctrl` + `1` y +`Ctrl` + `2` que le permiten saltar entre el script y los paneles de la consola +. + +Si R está listo para aceptar comandos, la consola de R muestra un mensaje `>`. If +it receives a command (by typing, copy-pasting or sending from the script +editor using `Ctrl` + `Enter`), R will try to execute it, and when +ready, will show the results and come back with a new `>` prompt to +wait for new commands. + +Si R todavía está esperando que ingrese más datos porque aún no está +completo, la consola mostrará un mensaje `+`. Significa que +no has terminado de ingresar un comando completo. This is because you have +not 'closed' a parenthesis or quotation, i.e. you don't have the same +number of left-parentheses as right-parentheses, or the same number of +opening and closing quotation marks. Cuando esto suceda, y usted +pensó que había terminado de escribir su comando, haga clic dentro de la ventana de la consola +y presione `Esc`; esto cancelará el comando incompleto y +lo devolverá al mensaje `>`. + +## ¿Cómo aprender más durante y después del curso? + +El material que cubrimos durante este curso le dará una +muestra inicial de cómo puede usar R para analizar datos para su propia +investigación. Sin embargo, necesitarás aprender más para realizar +operaciones avanzadas, como limpiar tu conjunto de datos, usar métodos estadísticos, +o crear hermosos gráficos[^inthiscoure]. La mejor manera de volverse +competente y eficiente en R, como con cualquier otra herramienta, es utilizarlo para +abordar sus preguntas de investigación reales. Como principiante, puede resultar +desalentador tener que escribir un script desde cero y, dado que muchas +personas ponen su código a disposición en línea, modifican el código existente para +que se adapte a su propósito. podría facilitarle el comienzo. + +[^inthiscoure]: Introduciremos la mayoría de estos (excepto las estadísticas) + aquí, pero solo lograremos arañar la superficie de la riqueza de + lo que es posible hacer con R. + +```{r kitten, results="markup", echo=FALSE, purl=FALSE, out.width="400px", fig.align="center"} +knitr::include_graphics("fig/kitten-try-things.jpg") +``` + +## Buscando ayuda + +### Utilice la interfaz de ayuda integrada de RStudio para buscar más información sobre las funciones de R + +```{r rstudiohelp, fig.cap="RStudio help interface.", results="markup", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/rstudiohelp.png") +``` + +Una de las formas más rápidas de obtener ayuda es utilizar la interfaz de ayuda +de RStudio. Este panel por defecto se puede encontrar en el panel inferior derecho +de RStudio. Como se ve en la captura de pantalla, al escribir la palabra +"Mean", RStudio intenta dar también una serie de sugerencias que podrían interesarle a +. La descripción se muestra luego en la ventana de visualización +. + +### Sé el nombre de la función que quiero usar, pero no estoy seguro de cómo usarla + +Si necesita ayuda con una función específica, digamos `barplot()`, +puede escribir: + +```{r, eval=FALSE, purl=TRUE} +?barplot +``` + +Si sólo necesita recordar los nombres de los argumentos, puede utilizar: + +```{r, eval=FALSE, purl=TRUE} +args(lm) +``` + +### Quiero usar una función que haga X, debe haber una función para ello pero no sé cuál... + +Si está buscando una función para realizar una tarea en particular, puede usar la función +`help.search()`, que se llama mediante el doble signo de interrogación `??`. +Sin embargo, esto solo busca en los paquetes instalados páginas de ayuda que coincidan +con su solicitud de búsqueda. + +```{r, eval=FALSE, purl=TRUE} +??kruskal +``` + +Si no puede encontrar lo que busca, puede utilizar +el sitio web [rdocumentation.org](https://www.rdocumentation.org) que busca +a través de los archivos de ayuda en todos los paquetes disponibles. + +Finalmente, una búsqueda genérica en Google o en Internet "R \" a menudo lo enviará +a la documentación del paquete correspondiente o a un foro útil donde alguien +más ya haya hecho su pregunta. + +### Estoy atascado... Me sale un mensaje de error que no entiendo + +Comience buscando en Google el mensaje de error. Sin embargo, esto no siempre funciona muy bien +porque a menudo, los desarrolladores de paquetes confían en la detección de errores proporcionada por R. Usted +termina con mensajes de error generales que pueden no ser muy útiles para diagnosticar un +problema (por ejemplo, "subíndice fuera de límites"). Si el mensaje es muy genérico, +también podrías incluir el nombre de la función o paquete que estás usando en tu consulta +. + +Sin embargo, deberías comprobar Stack Overflow. Busque usando la etiqueta `[r]`. La mayoría de las +preguntas ya han sido respondidas, pero el desafío es usar las +palabras correctas en la búsqueda para encontrar las +respuestas: + +[http://stackoverflow.com/questions/tagged/r](https://stackoverflow.com/questions/tagged/r) + +The [Introduction to R](https://cran.r-project.org/doc/manuals/R-intro.pdf) can +also be dense for people with little programming experience but it is a good +place to understand the underpinnings of the R language. + +Las [Preguntas frecuentes de R](https://cran.r-project.org/doc/FAQ/R-FAQ.html) son densas y técnicas +pero están llenas de información útil. + +### Pidiendo ayuda + +La clave para recibir ayuda de alguien es que comprenda rápidamente +tu problema. Deberías hacer que sea lo más fácil posible identificar dónde +podría estar el problema. + +Intente utilizar las palabras correctas para describir su problema. Por ejemplo, un paquete +no es lo mismo que una biblioteca. La mayoría de las personas +entenderán lo que quisiste decir, pero otros tienen sentimientos muy fuertes +sobre la diferencia de significado. El punto clave es que puede hacer que +las cosas sean confusas para las personas que intentan ayudarte. Sea lo más preciso +posible al describir su problema. + +Si es posible, intente reducir lo que no funciona a un simple ejemplo \*reproducible +\*. Si puede reproducir el problema usando un marco de datos muy pequeño +en lugar del de 50000 filas y 10000 columnas, proporcione el +pequeño con la descripción de su problema. Cuando sea apropiado, intente +para generalizar lo que está haciendo, de modo que incluso las personas que no están en su campo +puedan entender la pregunta. Por ejemplo, en lugar de utilizar un subconjunto +de su conjunto de datos real, cree uno pequeño (3 columnas, 5 filas) +genérico. Para obtener más información sobre cómo escribir un ejemplo +reproducible, consulte este artículo de Hadley +Wickham. + +Para compartir un objeto con otra persona, si es relativamente pequeño, +puedes usar la función `dput()`. Generará código R que se puede usar +para recrear exactamente el mismo objeto que el que está en la memoria: + +```{r, results="show", purl=TRUE} +## iris is an example data frame that comes with R and head() is a +## function that returns the first part of the data frame +dput(head(iris)) +``` + +If the object is larger, provide either the raw file (i.e., your CSV +file) with your script up to the point of the error (and after +removing everything that is not relevant to your +issue). Alternativamente, en particular si su pregunta no está relacionada +con un marco de datos, puede guardar cualquier objeto R en un archivo[^export]: + +```{r, eval=FALSE, purl=FALSE} +saveRDS(iris, file="/tmp/iris.rds") +``` + +Sin embargo, el contenido de este archivo no es legible por humanos y no se puede +publicar directamente en Stack Overflow. En su lugar, se puede enviar a alguien +por correo electrónico que pueda leerlo con el comando `readRDS()` (aquí +se supone que el archivo descargado está en una carpeta `Descargas` en el +directorio de inicio del usuario): + +```{r, eval=FALSE, purl=FALSE} +some_data <- readRDS(file="~/Downloads/iris.rds") +``` + +Por último, pero no menos importante, **siempre incluya la salida de `sessionInfo()`** +ya que proporciona información crítica sobre su plataforma, las versiones de R y +los paquetes que está usando y otra información que puede ser muy útil +para comprender su problema. + +```{r, results="show", purl=TRUE} +sessionInfo() +``` + +### ¿Dónde pedir ayuda? + +- La persona sentada a tu lado durante el curso. No dudes en + hablar con tu vecino durante el taller, comparar tus respuestas, + y pedir ayuda. +- Tus colegas amigables: si conoces a alguien con más experiencia + que tú, es posible que pueda y esté dispuesto a ayudarte. +- [Desbordamiento de pila](https://stackoverflow.com/questions/tagged/r): si + tu pregunta no ha sido respondida antes y está bien redactada, + es probable que obtengas una respuesta en menos de 5 min. Recuerde + seguir sus pautas sobre cómo hacer una buena + pregunta. +- La lista de correo de R-help + : es leída por + mucha gente (incluida la mayoría de el equipo central de R), mucha gente + publica en él, pero el tono puede ser bastante seco y no siempre + es muy acogedor para los nuevos usuarios. Si su pregunta es válida, es + probable que obtenga una respuesta muy rápido, pero no espere que llegue + con caras sonrientes. Además, aquí más que en cualquier otro lugar, asegúrese de + usar el vocabulario correcto (de lo contrario, podría obtener una respuesta que señale + el mal uso de sus palabras en lugar de responder su pregunta + ). También tendrá más éxito si su pregunta es sobre + una función base en lugar de un paquete específico. +- Si su pregunta es sobre un paquete específico, vea si hay una lista de correo + para él. Por lo general, se incluye en el archivo DESCRIPCIÓN + del paquete al que se puede acceder usando + `packageDescription("nombre-del-paquete")`. También puedes intentar enviar + un correo electrónico directamente al autor del paquete o abrir una incidencia en el repositorio de código + (por ejemplo, GitHub). +- También hay algunas listas de correo de temas específicos (SIG, + filogenética, etc...), la lista completa es + [aquí](https://www.r-project.org/ correo.html). + +### Más recursos + +- La [Guía de publicación](https://www.r-project.org/posting-guide.html) para + las listas de correo de R. + +- Cómo solicitar ayuda de R + + pautas útiles. + +- Esta publicación de blog de Jon + Skeet + tiene consejos bastante completos sobre cómo para hacer preguntas sobre programación. + +- El paquete [reprex](https://cran.rstudio.com/web/packages/reprex/) + es muy útil para crear ejemplos reproducibles cuando se solicita ayuda + . The rOpenSci community call "How to ask questions so they get + answered" (Github + link and video + recording) includes a presentation of + the reprex package and of its philosophy. + +## paquetes R + +### Cargando paquetes + +Como hemos visto anteriormente, los paquetes de R juegan un papel fundamental en R. Los +hacen uso de la funcionalidad de un paquete, suponiendo que esté instalado, +primero debemos cargarlo para poder usarlo. . Esto se hace con la función +`library()`. A continuación, cargamos `ggplot2`. + +```{r loadp, eval=FALSE, purl=TRUE} +library("ggplot2") +``` + +### Instalación de paquetes + +El repositorio de paquetes predeterminado es The _Comprehensive R Archive +Network_ (CRAN), y cualquier paquete que esté disponible en CRAN se puede +instalar con la función `install.packages()`. Debajo, por ejemplo, +instalamos el paquete `dplyr` del que aprenderemos más adelante. + +```{r craninstall, eval=FALSE, purl=TRUE} +install.packages("dplyr") +``` + +Este comando instalará el paquete `dplyr` así como todas sus +dependencias, es decir, todos los paquetes de los que depende para funcionar. + +Bioconductor mantiene otro importante repositorio de paquetes R. Los [paquetes de bioconductores](https://bioconductor.org/packages/release/BiocViews.html#___Software) se administran e instalan mediante un paquete dedicado, +, concretamente `BiocManager`, que se puede instalar desde CRAN con + +```{r, eval=FALSE, purl=TRUE} +install.packages("BiocManager") +``` + +Paquetes individuales como `SummarizedExperiment` (lo usaremos +más adelante), `DESeq2` (para análisis RNA-Seq) y cualquier otro de Bioconductor o CRAN se pueden instalar +con ` BiocManager::instalar`. + +```{r, eval=FALSE, purl=TRUE} +BiocManager::install("SummarizedExperiment") +BiocManager::install("DESeq2") +``` + +De forma predeterminada, `BiocManager::install()` también verificará todos los paquetes instalados y verá si hay versiones más nuevas disponibles. Si los hay, se los mostrará y le preguntará si desea "Actualizar todo/algo/ninguno". [a/s/n]:\` y luego espera tu respuesta. Si bien debe esforzarse por tener las versiones de paquetes más actualizadas, en la práctica recomendamos actualizar los paquetes solo en una nueva sesión de R antes de cargar cualquier paquete. + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Comience a usar R y RStudio + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/es/episodes/23-starting-with-r.Rmd b/locale/es/episodes/23-starting-with-r.Rmd new file mode 100644 index 000000000..72b4ffa37 --- /dev/null +++ b/locale/es/episodes/23-starting-with-r.Rmd @@ -0,0 +1,924 @@ +--- +source: Rmd +title: Introducción a R +teaching: 60 +exercises: 60 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Defina los siguientes términos en relación con R: objeto, asignación, llamada, función, argumentos, opciones. +- Asignar valores a objetos en R. +- Aprende a _nombrar_ objetos +- Utilice comentarios para informar el guión. +- Resolver operaciones aritméticas simples en R. +- Llame a funciones y use argumentos para cambiar sus opciones predeterminadas. +- Inspeccionar el contenido de los vectores y manipular su contenido. +- Subconjunto y extracción de valores de vectores. +- Analizar vectores con datos faltantes. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- Primeros comandos en R + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +> Este episodio se basa en la lección _Análisis de datos y +> Visualización en R para ecologistas_ de Data Carpentries. + +## Creando objetos en R + +Puede obtener resultados de R simplemente escribiendo matemáticas en la consola: + +```{r, purl=TRUE} +3 + 5 +12/7 +``` + +Sin embargo, para hacer cosas útiles e interesantes, necesitamos asignar _valores_ a +_objetos_. Para crear un objeto, debemos darle un nombre seguido del operador de asignación +`<-` y el valor que queremos darle: + +```{r, purl=TRUE} +weight_kg <- 55 +``` + +`<-` es el operador de asignación. Asigna valores a la derecha a +objetos a la izquierda. Entonces, después de ejecutar `x <- 3`, el valor de `x` es +`3`. La flecha se puede leer como 3 **entra** `x`. Por razones históricas +, también puedes usar `=` para tareas, pero no en todos los contextos +. Debido a las +[ligeras diferencias](https://blog.revolutionanalytics.com/2008/12/use-equals-or-arrow-for-assignment.html) +en la sintaxis, Es una buena práctica utilizar siempre `<-` para las tareas. + +In RStudio, typing Alt + \- (push Alt +at the same time as the \- key) will write `<-` in a single +keystroke in a PC, while typing Option + \- (push Option at the same time as the \- key) does the +same in a Mac. + +### Nombrar variables + +A los objetos se les puede dar cualquier nombre, como `x`, `current_temperature` o +`subject_id`. Quieres que los nombres de tus objetos sean explícitos y no demasiado +largos. No pueden comenzar con un número (`2x` no es válido, pero `x2` +sí lo es). R distingue entre mayúsculas y minúsculas (por ejemplo, `weight_kg` es diferente de +`Weight_kg`). Hay algunos nombres que no se pueden usar porque +son los nombres de funciones fundamentales en R (por ejemplo, `if`, `else`, +`for`, consulte +[ aquí](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Reserved.html) +para obtener una lista completa). En general, incluso si está permitido, es mejor +no usar otros nombres de funciones (por ejemplo, `c`, `T`, `mean`, `data`, `df`, +` pesos`). En caso de duda, consulte la ayuda para ver si el nombre ya está +en uso. También es mejor evitar los puntos (`.`) dentro del nombre de un objeto como en +`my.dataset`. There are many functions in R with dots in their names +for historical reasons, but because dots have a special meaning in R +(for methods) and other programming languages, it's best to avoid +them. También se recomienda utilizar sustantivos para nombres de objetos y verbos +para nombres de funciones. Es importante ser coherente en el estilo de +tu código (dónde colocas los espacios, cómo nombras los objetos, etc.). El uso de un estilo de codificación +consistente hace que su código sea más claro de leer para su +futuro yo y sus colaboradores. En R, algunas guías de estilo populares +son las de [Google](https://google.github.io/styleguide/Rguide.xml), las +[de tidyverse](https://style. tidyverse.org/) y la guía Bioconductor +style +. El +tidyverse es muy completo y puede parecer abrumador al principio +. Puede instalar el paquete +[**`lintr`**](https://github.com/jimhester/lintr) para +verificar automáticamente si hay problemas en el estilo de su código. + +> **Objetos versus variables**: Lo que se conoce como `objetos` en `R` se +> se conoce como `variables` en muchos otros lenguajes de programación. Dependiendo +> del contexto, `objeto` y `variable` pueden tener significados drásticamente +> diferentes. Sin embargo, en esta lección, las dos palabras se usan +> como sinónimos. Para obtener más información +> [ver aquí.](https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Objects) + +Al asignar un valor a un objeto, R no imprime nada. Usted +puede forzar a R a imprimir el valor usando paréntesis o escribiendo el nombre del objeto +: + +```{r, purl=TRUE} +weight_kg <- 55 # doesn't print anything +(weight_kg <- 55) # but putting parenthesis around the call prints the value of `weight_kg` +weight_kg # and so does typing the name of the object +``` + +Ahora que R tiene `weight_kg` en la memoria, podemos hacer aritmética con él. Por ejemplo +, es posible que deseemos convertir este peso en libras (el peso en libras es 2,2 veces el peso en kg): + +```{r, purl=TRUE} +2.2 * weight_kg +``` + +También podemos cambiar el valor de un objeto asignándole uno nuevo: + +```{r, purl=TRUE} +weight_kg <- 57.5 +2.2 * weight_kg +``` + +Esto significa que asignar un valor a un objeto no cambia los valores de +otros objetos. Por ejemplo, almacenemos el peso del animal en libras en un nuevo objeto +, `weight_lb`: + +```{r, purl=TRUE} +weight_lb <- 2.2 * weight_kg +``` + +y luego cambie `weight_kg` a 100. + +```{r} +weight_kg <- 100 +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +¿Cuál crees que es el contenido actual del objeto `weight_lb`? +¿126\.5 o 220? + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## Comentarios + +El carácter de comentario en R es `#`, cualquier cosa a la derecha de `#` en un script +será ignorada por R. Es útil dejar notas y +explicaciones en sus scripts. . + +RStudio hace que sea fácil comentar o descomentar un párrafo: después de +seleccionar las líneas que desea comentar, presione al mismo tiempo en +su teclado Ctrl + Mayús + C. If +you only want to comment out one line, you can put the cursor at any +location of that line (i.e. no need to select the whole line), then +press Ctrl + Shift + C. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío + +¿Cuáles son los valores después de cada declaración en lo siguiente? + +```{r, purl=TRUE} +mass <- 47.5 # mass? +age <- 122 # age? +mass <- mass * 2.0 # mass? +age <- age - 20 # age? +mass_index <- mass/age # mass_index? +``` + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## Funciones y sus argumentos. + +Las funciones son "scripts predefinidos" que automatizan conjuntos de comandos más complicados +incluyendo asignaciones de operaciones, etc. Muchas funciones están predefinidas o pueden +estar disponibles importando _paquetes_ R (más sobre esto más adelante). Una función +generalmente obtiene una o más entradas llamadas _argumentos_. Las funciones a menudo (pero no +siempre) devuelven un _valor_. Un ejemplo típico sería la función `sqrt()`. La entrada +(el argumento) debe ser un número y el valor de retorno (de hecho, la salida +) es la raíz cuadrada de ese número. Ejecutar una función ('ejecutarla') +se llama _llamar_ a la función. Un ejemplo de llamada a función es: + +```{r, eval=FALSE, purl=FALSE} +b <- raíz cuadrada (a) +``` + +Aquí, el valor de `a` se le da a la función `sqrt()`, la función `sqrt()` +calcula la raíz cuadrada y devuelve el valor que luego se asigna a +el objeto `b`. Esta función es muy sencilla, porque sólo necesita un argumento. + +The return 'value' of a function need not be numerical (like that of `sqrt()`), +and it also does not need to be a single item: it can be a set of things, or +even a dataset. Lo veremos cuando leamos archivos de datos en R. + +Los argumentos pueden ser cualquier cosa, no sólo números o nombres de archivos, sino también otros +objetos. Exactamente lo que significa cada argumento difiere según la función y se debe buscar +en la documentación (ver más abajo). Algunas funciones toman argumentos que +pueden ser especificados por el usuario o, si se omiten, tomar un valor _predeterminado_: +se denominan _opciones_. Las opciones se utilizan normalmente para alterar la forma en que opera la función +, como si ignora los 'valores incorrectos' o qué símbolo usar +en un gráfico. Sin embargo, si desea algo específico, puede especificar un valor +de su elección que se utilizará en lugar del valor predeterminado. + +Probemos una función que pueda tomar múltiples argumentos: `round()`. + +```{r, results="show", purl=TRUE} +redondo(3.14159) +``` + +Aquí, hemos llamado a `round()` con un solo argumento, `3.14159`, y +devolvió el valor `3`. Esto se debe a que el valor predeterminado es redondear al número entero +más cercano. Si queremos más dígitos, podemos ver cómo hacerlo obteniendo +información sobre la función "redonda". Podemos usar `args(round)` o mirar la ayuda +para esta función usando `?round`. + +```{r, results="show", purl=TRUE} +argumentos (redondo) +``` + +```{r, eval=FALSE, purl=TRUE} +?redondo +``` + +Vemos que si queremos una cantidad diferente de dígitos, podemos +escribir `dígitos=2` o la cantidad que queramos. + +```{r, results="show", purl=TRUE} +ronda(3.14159, dígitos = 2) +``` + +Si proporciona los argumentos exactamente en el mismo orden en que están definidos, +no tiene que nombrarlos: + +```{r, results="show", purl=TRUE} +ronda(3.14159, 2) +``` + +Y si nombras los argumentos, puedes cambiar su orden: + +```{r, results="show", purl=TRUE} +redondo(dígitos = 2, x = 3,14159) +``` + +Es una buena práctica poner los argumentos no opcionales (como el número que estás +redondeando) primero en tu llamada de función y especificar los nombres de todos los argumentos opcionales +. Si no lo hace, es posible que alguien que lea su código tenga que buscar la +definición de una función con argumentos desconocidos para comprender lo que está +haciendo. Al especificar el nombre de los argumentos, también protege +contra posibles cambios futuros en la interfaz de la función, que pueden +potencialmente agregar nuevos argumentos entre los existentes. + +## Vectores y tipos de datos + +Un vector es el tipo de datos más común y básico en R, y es prácticamente +el caballo de batalla de R. Un vector está compuesto por una serie de valores, como +números o caracteres. Podemos asignar una serie de valores a un vector usando +la función `c()`. Por ejemplo, podemos crear un vector de pesos de animales y asignarlo +a un nuevo objeto `weight_g`: + +```{r, purl=TRUE} +peso_g <- c(50, 60, 65, 82) +peso_g +``` + +Un vector también puede contener caracteres: + +```{r, purl=TRUE} +moléculas <- c("adn", "rna", "proteína") +moléculas +``` + +Las citas sobre "adn", "rna", etc. son esenciales aquí. Sin las comillas +, R asumirá que hay objetos llamados `dna`, `rna` y +`protein`. Como estos objetos no existen en la memoria de R, aparecerá +un mensaje de error. + +Hay muchas funciones que le permiten inspeccionar el contenido de un vector +. `length()` te dice cuántos elementos hay en un vector en particular: + +```{r, purl=TRUE} +longitud(peso_g) +longitud(moléculas) +``` + +Una característica importante de un vector es que todos los elementos son +el mismo tipo de datos. La función `class()` indica la clase (el tipo de elemento +) de un objeto: + +```{r, purl=TRUE} +clase(peso_g) +clase(moléculas) +``` + +La función `str()` proporciona una descripción general de la estructura de un objeto +y sus elementos. Es una función útil cuando se trabaja con +objetos grandes y complejos: + +```{r, purl=TRUE} +str(peso_g) +str(moléculas) +``` + +Puedes usar la función `c()` para agregar otros elementos a tu vector: + +```{r} +peso_g <- c(peso_g, 90) # agregar al final del vector +peso_g <- c(30, peso_g) # agregar al principio del vector +peso_g +``` + +En la primera línea, tomamos el vector original `weight_g`, agregamos el valor +`90` al final y guardamos el resultado nuevamente en +`weight_g`. Luego agregamos el valor `30` al principio, guardando nuevamente +el resultado nuevamente en `weight_g`. + +Podemos hacer esto una y otra vez para hacer crecer un vector o ensamblar un conjunto de datos +. Mientras programamos, esto puede ser útil para agregar resultados que estamos +recopilando o calculando. + +Un **vector atómico** es el **tipo de datos** R más simple y es un vector +lineal de un solo tipo. Arriba, vimos 2 de los 6 principales tipos de vectores \*\*atómicos +\*\* que usa R: `"carácter"` y `"numérico"` (o +`"doble"`). Estos son los componentes básicos a partir de los cuales se construyen todos los objetos R +. Los otros 4 tipos de **vectores atómicos** son: + +- `"lógico"` para `VERDADERO` y `FALSO` (el tipo de datos booleano) +- `"entero"` para números enteros (por ejemplo, `2L`, la `L` indica a R + que es un número entero) +- `"complejo"` para representar números complejos con partes + reales e imaginarias (por ejemplo, `1 + 4i`) y eso es todo lo que vamos a decir sobre ellos +- `"raw"` para flujos de bits que no discutiremos más + +Puede verificar el tipo de su vector usando la función `typeof()` +e ingresando su vector como argumento. + +Los vectores son una de las muchas **estructuras de datos** que utiliza R. Otros +importantes son listas (`list`), matrices (`matrix`), marcos de datos +(`data.frame`), factores (`factor`) y matrices (`array` ). + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +Hemos visto que los vectores atómicos pueden ser de tipo carácter, numérico (o +doble), entero y lógico. Pero ¿qué pasa si intentamos mezclar +estos tipos en un solo vector? + +::::::::::::::: solution + +## Solución + +R los convierte implícitamente para que todos sean del mismo tipo + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +¿Qué pasará en cada uno de estos ejemplos? (pista: use `class()` para +verificar el tipo de datos de sus objetos y escriba sus nombres para ver qué sucede): + +```{r, eval=TRUE} +num_char <- c(1, 2, 3, "a") +num_logic <- c(1, 2, 3, VERDADERO, FALSO) +char_logic <- c("a", " b", "c", VERDADERO) +complicado <- c(1, 2, 3, "4") +``` + +::::::::::::::: solution + +## Solución + +```{r, purl=TRUE} +class(num_char) +num_char +class(num_logical) +num_logical +class(char_logical) +char_logical +class(tricky) +tricky +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +¿Por qué crees que sucede? + +::::::::::::::: solution + +## Solución + +Los vectores pueden ser de un solo tipo de datos. R intenta convertir (coaccionar) +el contenido de este vector para encontrar un _denominador común_ que +no pierda ninguna información. + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +¿Cuántos valores en `combined_logic` son `"VERDADERO"` (como carácter) +en el siguiente ejemplo: + +```{r, eval=TRUE} +num_lógico <- c(1, 2, 3, VERDADERO) +char_lógico <- c("a", "b", "c", VERDADERO) +combinado_lógico <- c(núm_lógico, char_lógico ) +``` + +::::::::::::::: solution + +## Solución + +Sólo uno. No hay memoria de tipos de datos pasados y la coerción +ocurre la primera vez que se evalúa el vector. Por lo tanto, `VERDADERO` +en `num_logic` se convierte en un `1` antes de convertirse +en `"1"` en `combined_logic`. + +```{r} +lógico_combinado +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +En R, llamamos a convertir objetos de una clase a otra clase +_coerción_. Estas conversiones ocurren según una jerarquía, +, por la cual algunos tipos son preferentemente forzados a convertirse en otros tipos. ¿Puedes +dibujar un diagrama que represente la jerarquía de cómo se coaccionan estos tipos de datos +? + +::::::::::::::: solution + +## Solución + +lógico → numérico → carácter ← lógico + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +```{r, echo=FALSE, eval=FALSE, purl=TRUE} +## Hemos visto que los vectores atómicos pueden ser de tipo carácter, numérico, entero y +## lógico. Pero, ¿qué pasa si intentamos mezclar estos tipos en un solo +## vector? + +## ¿Qué pasará en cada uno de estos ejemplos? (pista: use `class()` para +## verificar el tipo de datos de su objeto) +num_char <- c(1, 2, 3, "a") + +num_logic <- c(1, 2, 3, VERDADERO) + +char_logic <- c("a", "b", "c", VERDADERO) + +complicado <- c(1, 2 , 3, "4") + +## ¿Por qué crees que sucede? + +## Probablemente hayas notado que objetos de diferentes tipos se +## convertidos en un tipo único y compartido dentro de un vector. En R, llamamos +## convertir objetos de una clase a otra clase +## _coerción_. Estas conversiones ocurren según una jerarquía, +## mediante la cual algunos tipos son preferentemente forzados a convertirse en otros tipos. ¿Puedes +## dibujar un diagrama que represente la jerarquía de cómo se coaccionan estos tipos de datos +##? +``` + +## Subconjunto de vectores + +Si queremos extraer uno o varios valores de un vector, debemos +proporcionar uno o varios índices entre corchetes. Por ejemplo: + +```{r, results="show", purl=TRUE} +moléculas <- c("adn", "rna", "péptido", "proteína") +moléculas[2] +moléculas[c(3, 2)] +``` + +También podemos repetir los índices para crear un objeto con más elementos +que el original: + +```{r, results="show", purl=TRUE} +more_molecules <- moléculas[c(1, 2, 3, 2, 1, 4)] +more_molecules +``` + +Los índices R comienzan en 1. Los lenguajes de programación como Fortran, MATLAB, +Julia y R comienzan a contar en 1, porque eso es lo que normalmente hacen los seres humanos +. Los lenguajes de la familia C (incluidos C++, Java, Perl, +y Python) cuentan desde 0 porque es más sencillo de hacer para las computadoras. + +Finalmente, también es posible obtener todos los elementos de un vector +excepto algunos elementos específicos que usan índices negativos: + +```{r} +moléculas ## todas las moléculas +moléculas[-1] ## todas menos la primera +moléculas[-c(1, 3)] ## todas menos la primera/tercera +moléculas [c(-1, -3)] ## todas menos la primera/tercera +``` + +## Subconjunto condicional + +Otra forma común de subconjunto es mediante el uso de un vector lógico. `TRUE` +seleccionará el elemento con el mismo índice, mientras que `FALSE` no: + +```{r, purl=TRUE} +peso_g <- c(21, 34, 39, 54, 55) +peso_g[c(VERDADERO, FALSO, VERDADERO, VERDADERO, FALSO)] +``` + +Normalmente, estos vectores lógicos no se escriben a mano, sino que son la salida +de otras funciones o pruebas lógicas. Por ejemplo, si +quisieras seleccionar solo los valores superiores a 50: + +```{r, purl=TRUE} +## will return logicals with TRUE for the indices that meet +## the condition +weight_g > 50 +## so we can use this to select only the values above 50 +weight_g[weight_g > 50] +``` + +Puede combinar varias pruebas usando `&` (ambas condiciones son verdaderas, +AND) o `|` (al menos una de las condiciones es verdadera, O): + +```{r, results="show", purl=TRUE} +peso_g[peso_g < 30 | peso_g > 50] +peso_g[peso_g >= 30 & peso_g == 21] +``` + +Aquí, `<` significa "menor que", `>` para "mayor que", `>=` para +"mayor o igual que" y `==` para "igual a". The double equal +sign `==` is a test for numerical equality between the left and right +hand sides, and should not be confused with the single `=` sign, which +performs variable assignment (similar to `<-`). + +Una tarea común es buscar determinadas cadenas en un vector. Uno podría +usar el operador "o" `|` para probar la igualdad de múltiples valores, pero +esto puede volverse tedioso rápidamente. La función `%in%` le permite +probar si se encuentra alguno de los elementos de un vector de búsqueda: + +```{r, purl=TRUE} +molecules <- c("dna", "rna", "protein", "peptide") +molecules[molecules == "rna" | molecules == "dna"] # returns both rna and dna +molecules %in% c("rna", "dna", "metabolite", "peptide", "glycerol") +molecules[molecules %in% c("rna", "dna", "metabolite", "peptide", "glycerol")] +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +¿Puedes entender por qué "cuatro" > "cinco" devuelve "VERDADERO"? + +::::::::::::::: solution + +## Solución + +```{r} +"cuatro" > "cinco" +``` + +Cuando se usa `>` o `<` en cadenas, R compara su orden alfabético. +Aquí `"cuatro"` viene después de `"cinco"` y, por lo tanto, es _mayor que_ +. + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## Nombres + +Es posible nombrar cada elemento de un vector. El fragmento de código siguiente +muestra un vector inicial sin ningún nombre, cómo se configuran los nombres y +se recuperan. + +```{r} +x <- c(1, 5, 3, 5, 10) +nombres(x) ## sin nombres +nombres(x) <- c("A", "B", " C", "D", "E") +nombres(x) ## ahora tenemos nombres +``` + +Cuando un vector tiene nombres, es posible acceder a los elementos por su nombre +, además de su índice. + +```{r} +x[c(1, 3)] +x[c("A", "C")] +``` + +## Datos perdidos + +Como R fue diseñado para analizar conjuntos de datos, incluye el concepto de +datos faltantes (lo cual es poco común en otros lenguajes de programación +). Los datos faltantes se representan en vectores como "NA". + +Al realizar operaciones con números, la mayoría de las funciones devolverán `NA` si +los datos con los que está trabajando incluyen valores faltantes. Esta característica +hace que sea más difícil pasar por alto los casos en los que se trata de +datos faltantes. Puede agregar el argumento `na.rm = TRUE` para calcular +el resultado ignorando los valores faltantes. + +```{r} +heights <- c(2, 4, 4, NA, 6) +mean(heights) +max(heights) +mean(heights, na.rm = TRUE) +max(heights, na.rm = TRUE) +``` + +Si sus datos incluyen valores faltantes, es posible que desee familiarizarse +con las funciones `is.na()`, `na.omit()` y `complete.cases()`. Consulte +a continuación para ver ejemplos. + +```{r} +## Extrae aquellos elementos a los que no les faltan valores. +heights[!is.na(heights)] + +## Devuelve el objeto sin casos incompletos. +## El objeto devuelto es un vector atómico de tipo `"numérico"` +## (o `"doble"`). +na.omit(heights) + +## Extrae aquellos elementos que sean casos completos. +## El objeto devuelto es un vector atómico de tipo `"numérico"` +## (o `"doble"`). +alturas[completos.casos(alturas)] +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +1. Usando este vector de alturas en pulgadas, cree un nuevo vector sin los NA. + +```{r} +alturas <- c(63, 69, 60, 65, NA, 68, 61, 70, 61, 59, 64, 69, 63, 63, NA, 72, 65, 64, 70, 63, 65) +``` + +2. Utilice la función `median()` para calcular la mediana del vector `alturas`. +3. Usa R para calcular cuántas personas en el grupo miden más de 67 pulgadas. + +::::::::::::::: solution + +## Solución + +```{r, purl=TRUE} +alturas_no_na <- alturas[!is.na(alturas)] +## o +alturas_no_na <- na.omit(alturas) +``` + +```{r, purl=TRUE} +mediana (alturas, na.rm = VERDADERO) +``` + +```{r, purl=TRUE} +alturas_arriba_67 <- alturas_no_na[alturas_no_na > 67] +longitud(alturas_arriba_67) +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## Generando vectores {#sec:genvec} + +```{r, echo=FALSE} +conjunto.semilla(1) +``` + +### Constructores + +Existen algunas funciones para generar vectores de diferente tipo. Para +generar un vector de números, se puede usar el constructor `numeric()` +, proporcionando la longitud del vector de salida como parámetro +. Los valores se inicializarán con 0. + +```{r, purl=TRUE} +numérico(3) +numérico(10) +``` + +Tenga en cuenta que si pedimos un vector de números de longitud 0, obtenemos +exactamente eso: + +```{r, purl=TRUE} +numérico(0) +``` + +Hay constructores similares para caracteres y lógicos, llamados +`character()` y `logic()` respectivamente. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +¿Cuáles son los valores predeterminados para los vectores lógicos y de caracteres? + +::::::::::::::: solution + +## Solución + +```{r, purl=TRUE} +carácter(2) ## el carácter vacío +lógico(2) ## FALSO +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +### Replicar elementos + +La función `rep` permite repetir un valor un cierto número de +veces. Si queremos iniciar un vector de numéricos de longitud 5 con +el valor -1, por ejemplo, podríamos hacer lo siguiente: + +```{r, purl=TRUE} +representante(-1, 5) +``` + +De manera similar, para generar un vector poblado con valores faltantes, lo cual +suele ser una buena forma de comenzar, sin establecer suposiciones sobre los datos +que se recopilarán: + +```{r, purl=TRUE} +representante(NA, 5) +``` + +`rep` puede tomar vectores de cualquier longitud como entrada (arriba, usamos vectores +de longitud 1) y de cualquier tipo. Por ejemplo, si queremos repetir los valores +1, 2 y 3 cinco veces, haríamos lo siguiente: + +```{r, purl=TRUE} +representante(c(1, 2, 3), 5) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +¿Qué pasaría si quisiéramos repetir los valores 1, 2 y 3 cinco veces, pero +obtuviéramos cinco 1, cinco 2 y cinco 3 en ese orden? Hay dos posibilidades +; consulte `?rep` o `?sort` para obtener ayuda. + +::::::::::::::: solution + +## Solución + +```{r, purl=TRUE} +rep(c(1, 2, 3), each = 5) +sort(rep(c(1, 2, 3), 5)) +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +### Generación de secuencia + +Otra función muy útil es `seq`, para generar una secuencia de +números. Por ejemplo, para generar una secuencia de números enteros del 1 al 20 +en pasos de 2, se usaría: + +```{r, purl=TRUE} +seq(de = 1, a = 20, por = 2) +``` + +El valor predeterminado de `by` es 1 y, dado que con frecuencia se usa la generación de una secuencia +de un valor a otro con pasos de 1, +hay un atajo: + +```{r, purl=TRUE} +secuencia (1, 5, 1) +secuencia (1, 5) ## predeterminado por +1:5 +``` + +Para generar una secuencia de números del 1 al 20 de longitud final de 3, +se usaría: + +```{r, purl=TRUE} +seq(de = 1, a = 20, longitud.salida = 3) +``` + +### Muestras aleatorias y permutaciones. + +Un último grupo de funciones útiles son aquellas que generan datos +aleatorios. El primero, "muestra", genera una permutación aleatoria de +otro vector. Por ejemplo, para dibujar un orden aleatorio para el examen oral de 10 estudiantes +, primero le asigno a cada estudiante un número del 1 al diez (por ejemplo, +según el orden alfabético de su nombre) y luego: + +```{r, purl=TRUE} +muestra(1:10) +``` + +Sin más argumentos, `sample` devolverá una permutación de todos los +elementos del vector. Si quiero una muestra aleatoria de un cierto tamaño, +establecería este valor como segundo argumento. A continuación, muestro 5 letras +aleatorias del alfabeto contenido en el vector de "letras" predefinido: + +```{r, purl=TRUE} +muestra(letras, 5) +``` + +Si quisiera una salida más grande que el vector de entrada, o poder +dibujar algunos elementos varias veces, necesitaría establecer el argumento `replace` +en `TRUE`: + +```{r, purl=TRUE} +muestra(1:5, 10, reemplazar = VERDADERO) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +Al probar las funciones anteriores, te habrás dado cuenta de que las muestras +son realmente aleatorias y que no se obtiene la misma permutación +dos veces. Para poder reproducir estos sorteos aleatorios, se puede +configurar la semilla de generación de números aleatorios manualmente con `set.seed()` +antes de extraer la muestra aleatoria. + +Pruebe esta característica con su vecino. Primero dibuja dos permutaciones aleatorias +de `1:10` de forma independiente y observa que obtienes +resultados diferentes. + +Ahora establezca la semilla con, por ejemplo, `set.seed(123)` y repita el sorteo aleatorio +. Observe que ahora obtiene los mismos sorteos aleatorios. + +Repita colocando una semilla diferente. + +::::::::::::::: solution + +## Solución + +Diferentes permutaciones + +```{r, purl=TRUE} +muestra(1:10) +muestra(1:10) +``` + +Mismas permutaciones con la semilla 123. + +```{r, purl=TRUE} +set.seed(123) +muestra(1:10) +set.seed(123) +muestra(1:10) +``` + +Una semilla diferente + +```{r, purl=TRUE} +set.seed(1) +muestra(1:10) +set.seed(1) +muestra(1:10) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +### Extraer muestras de una distribución normal + +La última función que vamos a ver es `rnorm`, que extrae una muestra aleatoria +de una distribución normal. A continuación se muestran dos distribuciones normales de medias 0 +y 100 y desviaciones estándar 1 y 5, anotadas _N(0, 1)_ y +_N(100, 5)_. + +```{r, echo=FALSE, fig.width=12, fig.height=6, fig.cap="Two normal distributions: *N(0, 1)* on the left and *N(100, 5)* on the right."} +par(mfrow = c(1, 2)) +plot(densidad(rnorm(1000)), main = "", sub = "N(0, 1)") +plot(densidad (norm(1000, 100, 5)), principal = "", sub = "N(100, 5)") +``` + +Los tres argumentos, `n`, `mean` y `sd`, definen el tamaño de la muestra +y los parámetros de la distribución normal, es decir, la media +y su desviación estándar. Los valores predeterminados de este último son 0 y 1. + +```{r, purl=TRUE} +norma(5) +norma(5, 2, 2) +norma(5, 100, 5) +``` + +Ahora que hemos aprendido cómo escribir scripts y los conceptos básicos de las estructuras de datos +de R, estamos listos para comenzar a trabajar con datos más grandes y +aprender sobre marcos de datos. + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Cómo interactuar con R + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/es/episodes/25-starting-with-data.Rmd b/locale/es/episodes/25-starting-with-data.Rmd new file mode 100644 index 000000000..24e3b0832 --- /dev/null +++ b/locale/es/episodes/25-starting-with-data.Rmd @@ -0,0 +1,784 @@ +--- +source: Rmd +title: Partiendo de datos +teaching: 30 +exercises: 30 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Describir un objeto de tipo `data.frame`. +- Cargar datos externos desde un archivo .csv a un objecto `data.frame`. +- Resumir el contenido de un marco de datos. +- Describe qué es un factor. +- Convertir entre cadenas y factores. +- Reordenar y cambiar el nombre de los factores. +- Dar formato a las fechas. +- Exportar y guardar datos. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- Primer análisis de datos en R + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +> Este episodio se basa en la lección _Análisis de datos y +> Visualización en R para ecologistas_ de Data Carpentries. + +## Presentación de los datos de expresión génica. + +Vamos a utilizar parte de los datos publicados por Blackmore , _El efecto +de la infección de las vías respiratorias superiores sobre los cambios transcriptómicos en el +SNC_. El objetivo del estudio fue determinar el efecto de una +infección de las vías respiratorias superiores sobre los cambios en la transcripción del ARN que ocurren +en el cerebelo y la médula espinal después de la infección. Se inocularon ocho ratones C57BL/6 de +semanas de edad de sexo coincidente con solución salina o con Influenza A por +vía intranasal y se evaluaron los cambios transcriptómicos en el cerebelo y +tejidos de la médula espinal mediante ARN- seq en los días 0 +(no infectados), 4 y 8. + +El conjunto de datos se almacena como un archivo de valores separados por comas (CSV). Cada fila +contiene información para una única medición de expresión de ARN, y las primeras once columnas +representan: + +| Columna | Descripción | +| --------- | ---------------------------------------------------------------------------------------------------------------------------- | +| gene | El nombre del gen que se midió. | +| muestra | El nombre de la muestra en la que se midió la expresión genética. | +| expresión | El valor de la expresión genética. | +| organismo | El organismo/especie: aquí todos los datos provienen de ratones. | +| edad | La edad del ratón (aquí todos los ratones tenían 8 semanas) | +| sexo | El sexo del ratón | +| infección | El estado de infección del ratón, es decir, infectado con gripe A o no infectado. | +| cepa | La cepa de influenza A. | +| tiempo | La duración de la infección (en días). | +| tejido | El tejido que se utilizó para el experimento de expresión génica, es decir, el cerebelo o la médula espinal. | +| ratón | El identificador único del mouse. | + +Usaremos la función R `download.file()` para descargar el +archivo CSV que contiene los datos de expresión genética, y usaremos +`read.csv()` para cargar en la memoria el contenido del archivo CSV como un +objeto de clase `data.frame`. Dentro del comando `download.file`, la primera entrada +es una cadena de caracteres con la URL de origen. Esta URL de origen +descarga un archivo CSV desde un repositorio de GitHub. El texto después de la coma +("data/rnaseq.csv"`) es el destino del archivo en su máquina local +. Necesitará tener una carpeta en su máquina llamada +`"data"`donde descargará el archivo. Entonces, este comando descarga el archivo remoto +, lo llama`"rnaseq.csv"`y lo agrega a una carpeta +preexistente llamada`"data"\`. + +```{r, eval=TRUE} +download.file(url = "https://github.com/carpentries-incubator/bioc-intro/raw/main/episodes/data/rnaseq.csv", + destfile = "data/rnaseq.csv") +``` + +Ahora está listo para cargar los datos: + +```{r, eval=TRUE, purl=TRUE} +rna <- read.csv("data/rnaseq.csv") +``` + +Esta declaración no produce ningún resultado porque, como +recordarás, las asignaciones no muestran nada. Si queremos comprobar que +nuestros datos han sido cargados, podemos ver el contenido del marco de datos +escribiendo su nombre: + +```{r, eval=FALSE} +rna +``` + +Guau... eso fue mucho resultado. Al menos significa que los datos se cargaron +correctamente. Revisemos la parte superior (las primeras 6 líneas) de este marco de datos +usando la función `head()`: + +```{r, purl=TRUE} +head(rna) +## Try also +## View(rna) +``` + +**Nota** + +`read.csv()` asume que los campos están delimitados por comas; sin embargo, en +varios países, la coma se usa como separador decimal y el +punto y coma (;) se usa como campo delineador. Si desea leer en +este tipo de archivos en R, puede usar la función `read.csv2()`. +se comporta exactamente como `read.csv()` pero usa diferentes parámetros para +los separadores decimales y de campo. Si está trabajando con otro formato +, el usuario puede especificar ambos. Consulte la ayuda para +`read.csv()` escribiendo `?read.csv` para obtener más información. También existe la función +`read.delim()` para leer archivos de datos separados por tabulaciones. Es importante +tener en cuenta que todas estas funciones son en realidad funciones contenedoras para +la función principal `read.table()` con diferentes argumentos. Como tal, +los datos anteriores también podrían haberse cargado usando `read.table()` +con el argumento de separación como `,`. El código es el siguiente: + +```{r, eval=TRUE, purl=TRUE} +rna <- read.table(file = "data/rnaseq.csv", + sep = ",", + header = TRUE) +``` + +El argumento del encabezado debe establecerse en VERDADERO para poder leer los encabezados +ya que, de forma predeterminada, `read.table()` tiene el argumento del encabezado establecido en +FALSO. + +## ¿Qué son los marcos de datos? + +Los marcos de datos son la estructura de datos _de facto_ para la mayoría de los datos tabulares, +y lo que usamos para estadísticas y gráficos. + +Un marco de datos se puede crear a mano, pero lo más común es que +se generen mediante las funciones `read.csv()` o `read.table()`; en otras +palabras, al importar hojas de cálculo desde su disco duro (o la web). + +Un marco de datos es la representación de datos en el formato de una tabla +donde las columnas son vectores que tienen la misma longitud. Debido a que las columnas +son vectores, cada columna debe contener un único tipo de datos +(por ejemplo, caracteres, números enteros, factores). Por ejemplo, aquí hay una figura +que representa un marco de datos que comprende un vector numérico, un carácter y un vector lógico +. + +![](./fig/data-frame.svg) + +Podemos ver esto al inspeccionar la estructura strde un marco de datos +con la función `str()`: + +```{r} +str(rna) +``` + +## Inspeccionando objetos `data.frame` + +Ya vimos cómo las funciones `head()` y `str()` pueden ser útiles para +comprobar el contenido y la estructura de un marco de datos. Aquí hay una +lista no exhaustiva de funciones para tener una idea del +contenido/estructura de los datos. ¡Probémoslos! + +**Tamaño**: + +- `dim(rna)` - devuelve un vector con el número de filas como el primer elemento + y el número de columnas como el segundo elemento (las + **dim**ensiones del objeto ). +- `nrow(rna)` - devuelve el número de filas. +- `ncol(rna)` - devuelve el número de columnas. + +**Contenido**: + +- `head(rna)` - muestra las primeras 6 filas. +- `tail(rna)` - muestra las últimas 6 filas. + +**Nombres**: + +- `names(rna)` - devuelve los nombres de las columnas (sinónimo de `colnames()` para + objetos `data.frame`). +- `rownames(rna)` - devuelve los nombres de las filas. + +**Resumen**: + +- `str(rna)` - estructura del objeto e información sobre la clase + , longitud y contenido de cada columna. +- `summary(rna)`: resumen de estadísticas para cada columna. + +Nota: la mayoría de estas funciones son "genéricas", se pueden usar en otros tipos de objetos +además de `data.frame`. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +Según el resultado de `str(rna)`, ¿puedes responder las siguientes +preguntas? + +- ¿Cuál es la clase del objeto `rna`? +- ¿Cuántas filas y cuántas columnas hay en este objeto? + +::::::::::::::: solution + +## Solución + +- clase: marco de datos +- cuantas filas: 66465, cuantas columnas: 11 + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Indexación y subconjunto de marcos de datos + +Nuestro marco de datos `rna` tiene filas y columnas (tiene 2 dimensiones); Si +queremos extraer algunos datos específicos de él, debemos especificar las +"coordenadas" que queremos. Los números de fila van primero, seguidos de +números de columna. Sin embargo, tenga en cuenta que diferentes formas de especificar estas coordenadas +conducen a resultados con diferentes clases. + +```{r, eval=FALSE, purl=TRUE} +# first element in the first column of the data frame (as a vector) +rna[1, 1] +# first element in the 6th column (as a vector) +rna[1, 6] +# first column of the data frame (as a vector) +rna[, 1] +# first column of the data frame (as a data.frame) +rna[1] +# first three elements in the 7th column (as a vector) +rna[1:3, 7] +# the 3rd row of the data frame (as a data.frame) +rna[3, ] +# equivalent to head_rna <- head(rna) +head_rna <- rna[1:6, ] +head_rna +``` + +`:` es una función especial que crea vectores numéricos de números enteros en +orden creciente o decreciente, pruebe `1:10` y `10:1` para la instancia +. Consulte la sección @ref(sec:genvec) para obtener más detalles. + +También puedes excluir ciertos índices de un marco de datos usando el signo "`-`": + +```{r, eval=FALSE, purl=TRUE} +rna[, -1] ## The whole data frame, except the first column +rna[-c(7:66465), ] ## Equivalent to head(rna) +``` + +Los marcos de datos se pueden subconjuntos llamando a índices (como se mostró anteriormente), +pero también llamando directamente a sus nombres de columnas: + +```{r, eval=FALSE, purl=TRUE} +rna["gene"] # Result is a data.frame +rna[, "gene"] # Result is a vector +rna[["gene"]] # Result is a vector +rna$gene # Result is a vector +``` + +En RStudio, puede utilizar la función de autocompletar para obtener los nombres completos y +correctos de las columnas. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío + +1. Cree un `data.frame` (`rna_200`) que contenga solo los datos en + fila 200 del conjunto de datos `rna`. + +2. ¿Observó cómo `nrow()` le dio el número de filas en un `data.frame`? + +- Use ese número para extraer solo la última fila en el marco de datos inicial + `rna`. + +- Compare eso con lo que ve como la última fila usando `tail()` para + y asegúrese de que cumpla con las expectativas. + +- Saque la última fila usando `nrow()` en lugar del número de fila. + +- Cree un nuevo marco de datos (`rna_last`) a partir de esa última fila. + +3. Utilice `nrow()` para extraer la fila que está en el medio del marco de datos + `rna`. Almacene el contenido de esta fila en un objeto + llamado `rna_middle`. + +4. Combine `nrow()` con la notación `-` anterior para reproducir el comportamiento + de `head(rna)`, manteniendo solo la primera a la sexta + filas del conjunto de datos de rna. + +::::::::::::::: solution + +## Solución + +```{r, purl=TRUE} +## 1. +rna_200 <- rna[200, ] +## 2. +## Saving `n_rows` to improve readability and reduce duplication +n_rows <- nrow(rna) +rna_last <- rna[n_rows, ] +## 3. +rna_middle <- rna[n_rows / 2, ] +## 4. +rna_head <- rna[-(7:n_rows), ] +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Factores + +Los factores representan **datos categóricos**. Se almacenan como números enteros +asociados con etiquetas y pueden estar ordenados o desordenados. Si bien los factores +parecen (y a menudo se comportan) como vectores de caracteres, en realidad R los trata +como vectores enteros. Por lo tanto, debe tener mucho cuidado +al tratarlos como cadenas. + +Una vez creados, los factores solo pueden contener un conjunto predefinido de valores, +conocidos como _niveles_. De forma predeterminada, R siempre ordena los niveles en orden alfabético +. Por ejemplo, si tienes un factor con 2 niveles: + +```{r, purl=TRUE} +sex <- factor(c("male", "female", "female", "male", "female")) +``` + +R will assign `1` to the level `"female"` and `2` to the level +`"male"` (because `f` comes before `m`, even though the first element +in this vector is `"male"`). Puedes ver esto usando la función +`levels()` y puedes encontrar el número de niveles usando `nlevels()`: + +```{r, purl=TRUE} +levels(sex) +nlevels(sex) +``` + +A veces, el orden de los factores no importa, otras veces +es posible que desee especificar el orden porque es significativo (por ejemplo, "bajo", +"medio", "alto"), mejora su visualización, o es requerido +por un tipo particular de análisis. Aquí, una forma de reordenar nuestros niveles +en el vector `sex` sería: + +```{r, purl=TRUE} +sex ## current order +sex <- factor(sex, levels = c("male", "female")) +sex ## after re-ordering +``` + +En la memoria de R, estos factores están representados por números enteros (1, 2, 3), +pero son más informativos que los números enteros porque los factores son auto +y describen: `"femenino"`, `"masculino" ` es más descriptivo que `1`, +`2`. ¿Cuál es "masculino"? No podrías saberlo solo por los datos enteros +. Los factores, por otro lado, tienen esta información incorporada. +Es particularmente útil cuando hay muchos niveles (como el biotipo del gen +en nuestro conjunto de datos de ejemplo). + +Cuando sus datos se almacenan como un factor, puede usar la función `plot()` +para obtener un vistazo rápido al número de observaciones +representadas por cada nivel de factor. Veamos la cantidad de hombres +y mujeres en nuestros datos. + +```{r firstfactorplot, fig.cap="Bar plot of the number of females and males.", purl=TRUE} +plot(sex) +``` + +### Convertirse en personaje + +Si necesita convertir un factor en un vector de caracteres, utilice +`as.character(x)`. + +```{r, purl=TRUE} +as.character(sex) +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +### Factores de cambio de nombre + +Si queremos cambiar el nombre de estos factores, basta con cambiar sus +niveles: + +```{r, purl=TRUE} +levels(sex) +levels(sex) <- c("M", "F") +sex +plot(sex) +``` + +:::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +- Cambie el nombre de "F" y "M" a "Mujer" y "Masculino" respectivamente. + +::::::::::::::: solution + +## Solución + +```{r, eval=TRUE, purl=TRUE} +levels(sex) +levels(sex) <- c("Male", "Female") +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +Hemos visto cómo se crean los marcos de datos cuando se usa `read.csv()`, pero +también se pueden crear a mano con la función `data.frame()`. +Hay algunos errores en este "data.frame" hecho a mano. ¿Puedes +detectarlos y solucionarlos? ¡No dudes en experimentar! + +```{r, eval=FALSE} +animal_data <- data.frame( + animal = c(dog, cat, sea cucumber, sea urchin), + feel = c("furry", "squishy", "spiny"), + weight = c(45, 8 1.1, 0.8)) +``` + +::::::::::::::: solution + +## Solución + +- Faltan citas alrededor de los nombres de los animales. +- falta una entrada en la columna "sensación" (probablemente para uno de los animales peludos) +- falta una coma en la columna de peso + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +¿Puedes predecir la clase para cada una de las columnas en el siguiente ejemplo +? + +Comprueba tus conjeturas usando `str(country_climate)`: + +- ¿Son lo que esperabas? ¿Por qué? ¿Por qué no? + +- Intente nuevamente agregando `stringsAsFactors = TRUE` después de la última variable + al crear el marco de datos. ¿Qué está pasando ahora? + `stringsAsFactors` también se puede configurar al leer + hojas de cálculo basadas en texto en R usando `read.csv()`. + +```{r, eval=FALSE, purl=TRUE} +country_climate <- data.frame( + country = c("Canada", "Panama", "South Africa", "Australia"), + climate = c("cold", "hot", "temperate", "hot/temperate"), + temperature = c(10, 30, 18, "15"), + northern_hemisphere = c(TRUE, TRUE, FALSE, "FALSE"), + has_kangaroo = c(FALSE, FALSE, FALSE, 1) + ) +``` + +::::::::::::::: solution + +## Solución + +```{r, eval=TRUE, purl=TRUE} +country_climate <- data.frame( + country = c("Canada", "Panama", "South Africa", "Australia"), + climate = c("cold", "hot", "temperate", "hot/temperate"), + temperature = c(10, 30, 18, "15"), + northern_hemisphere = c(TRUE, TRUE, FALSE, "FALSE"), + has_kangaroo = c(FALSE, FALSE, FALSE, 1) + ) +str(country_climate) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +La conversión automática de tipos de datos es a veces una bendición, a veces una +molestia. Tenga en cuenta que existe, aprenda las reglas y verifique que los datos +que importe en R sean del tipo correcto dentro de su marco de datos. De lo contrario, úselo +a su favor para detectar errores que podrían haberse introducido durante la entrada de datos +(una letra en una columna que solo debe contener números, por ejemplo). + +Obtenga más información en este tutorial de RStudio + + +## matrices + +Antes de continuar, ahora que hemos aprendido sobre los marcos de datos, recapitulemos +la instalación del paquete y aprendamos sobre un nuevo tipo de datos, a saber, la +`matriz`. Al igual que un `data.frame`, una matriz tiene dos dimensiones, filas y +columnas. Pero la principal diferencia es que todas las celdas de una `matriz` deben +ser del mismo tipo: `numérica`, `carácter`, `lógica`, ... En ese +respecto, las matrices están más cerca de un "vector" que de un "marco.de.datos". + +El constructor predeterminado para una matriz es "matriz". Se necesita un vector de +valores para poblar la matriz y el número de filas y/o +columnas[^ncol]. Los valores se ordenan a lo largo de las columnas, como se ilustra +a continuación. + +```{r mat1, purl=TRUE} +m <- matrix(1:9, ncol = 3, nrow = 3) +m +``` + +[^ncol]: O el número de filas o columnas es suficiente, ya que el otro se puede deducir de la longitud de los valores. Pruebe qué sucede si los valores y el número de filas/columnas no cuadran. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +Usando la función `installed.packages()`, cree una matriz de `caracteres` +que contenga la información sobre todos los paquetes actualmente instalados en +su computadora. Explorarlo. + +::::::::::::::: solution + +## Solución: + +```{r pkg_sln, eval=FALSE, purl=TRUE} +## create the matrix +ip <- installed.packages() +head(ip) +## try also View(ip) +## number of package +nrow(ip) +## names of all installed packages +rownames(ip) +## type of information we have about each package +colnames(ip) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +A menudo resulta útil crear grandes matrices de datos aleatorios como datos de prueba +. El siguiente ejercicio le pide que cree dicha matriz con datos aleatorios +extraídos de una distribución normal de media 0 y desviación estándar +1, lo cual se puede hacer con la función `rnorm()`. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +Construya una matriz de dimensión 1000 por 3 de datos distribuidos normalmente +(media 0, desviación estándar 1) + +::::::::::::::: solution + +## Solución + +```{r rnormmat_sln, purl=TRUE} +set.seed(123) +m <- matrix(rnorm(3000), ncol = 3) +dim(m) +head(m) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Formato de fechas + +Uno de los problemas más comunes que los nuevos (¡y experimentados!) Los usuarios de R +convierten la información de fecha y hora en una variable que es +apropiada y utilizable durante los análisis. + +### Nota sobre fechas en programas de hojas de cálculo + +Las fechas en las hojas de cálculo generalmente se almacenan en una sola columna. Si bien +esta parece la forma más natural de registrar fechas, en realidad no es +la mejor práctica. Una aplicación de hoja de cálculo mostrará las fechas de una manera +aparentemente correcta (para un observador humano), pero la forma en que realmente +maneja y almacena las fechas puede ser problemática. A menudo es mucho más seguro +almacenar fechas con AÑO, MES y DÍA en columnas separadas o +como AÑO y DÍA DEL AÑO en columnas separadas. + +Programas de hojas de cálculo como LibreOffice, Microsoft Excel, OpenOffice, +Gnumeric,... tienen formas diferentes (y a menudo incompatibles) de codificar +fechas (incluso para el mismo programa entre versiones y sistemas operativos +). Además, Excel puede [convertir cosas que no son fechas en +fechas](https://nsaunders.wordpress.com/2012/10/22/gene-name-errors-and-excel-lessons-not -aprendido/) +(@Zeeberg:2004), por ejemplo nombres o identificadores como MAR1, DEC1, +OCT4. Entonces, si evitas el formato de fecha en general, es más fácil +identificar estos problemas. + +La sección Fechas como +datos +de la lección Carpintería de datos proporciona Ideas adicionales +sobre los peligros de las fechas con hojas de cálculo. + +Vamos a utilizar la función `ymd()` del paquete +**`lubridate`** (que pertenece al **`tidyverse`**; aprende más +[aquí] (https://www.tidyverse.org/)). . **`lubridate`** se instala +como parte de la instalación de **`tidyverse`**. Cuando cargas +**`tidyverse`** (`library(tidyverse)`), los paquetes principales (los +paquetes utilizados en la mayoría de los análisis de datos) se cargan. **`lubridate`** +sin embargo no pertenece al tidyverse principal, por lo que debes cargarlo +explícitamente con `library(lubridate)`. + +Comience cargando el paquete requerido: + +```{r loadlibridate, message=FALSE, purl=TRUE} +library("lubridate") +``` + +`ymd()` toma un vector que representa año, mes y día, y lo convierte +en un vector `Date`. `Date` es una clase de datos reconocida por R como +siendo una fecha y puede manipularse como tal. El argumento que requiere la función +es flexible, pero, como práctica recomendada, es un vector de caracteres +con el formato "AAAA-MM-DD". + +Creemos un objeto de fecha e inspeccionemos la estructura: + +```{r, purl=TRUE} +my_date <- ymd("2015-01-01") +str(my_date) +``` + +Ahora peguemos el año, el mes y el día por separado; obtenemos el mismo resultado: + +```{r, purl=TRUE} +# sep indicates the character to use to separate each component +my_date <- ymd(paste("2015", "1", "1", sep = "-")) +str(my_date) +``` + +Familiaricémonos ahora con una canalización típica de manipulación de fechas +. Los pequeños datos a continuación han almacenado fechas en diferentes columnas "año", +"mes" y "día". + +```{r, purl=TRUE} +x <- data.frame(year = c(1996, 1992, 1987, 1986, 2000, 1990, 2002, 1994, 1997, 1985), + month = c(2, 3, 3, 10, 1, 8, 3, 4, 5, 5), + day = c(24, 8, 1, 5, 8, 17, 13, 10, 11, 24), + value = c(4, 5, 1, 9, 3, 8, 10, 2, 6, 7)) +x +``` + +Ahora aplicamos esta función al conjunto de datos `x`. Primero creamos un vector de caracteres +a partir de las columnas `año`, `mes` y `día` de `x` +usando `paste()`: + +```{r, purl=TRUE} +paste(x$year, x$month, x$day, sep = "-") +``` + +Este vector de caracteres se puede utilizar como argumento para `ymd()`: + +```{r, purl=TRUE} +ymd(paste(x$year, x$month, x$day, sep = "-")) +``` + +El vector "Fecha" resultante se puede agregar a "x" como una nueva columna llamada "fecha": + +```{r, purl=TRUE} +x$date <- ymd(paste(x$year, x$month, x$day, sep = "-")) +str(x) # notice the new column, with 'date' as the class +``` + +Asegurémonos de que todo funcionó correctamente. Una forma de inspeccionar la +nueva columna es usar `summary()`: + +```{r, purl=TRUE} +summary(x$date) +``` + +Tenga en cuenta que `ymd()` espera tener el año, mes y día, en ese orden +. Si tiene, por ejemplo, día, mes y año, necesitará +`dmy()`. + +```{r, purl=TRUE} +dmy(paste(x$day, x$month, x$year, sep = "-")) +``` + +`lubdridate` tiene muchas funciones para abordar todas las variaciones de fechas. + +## Resumen de objetos R + +Hasta ahora, hemos visto varios tipos de objetos R que varían en el número +de dimensiones y si pueden almacenar uno o varios tipos de datos +: + +- **`vector`**: una dimensión (tienen una longitud), un solo tipo de datos. +- **`matriz`**: dos dimensiones, un solo tipo de datos. +- **`data.frame`**: dos dimensiones, un tipo por columna. + +## Liza + +Un tipo de datos que aún no hemos visto, pero que es útil conocer, y +se desprende del resumen que acabamos de ver son listas: + +- **`lista`**: una dimensión, cada elemento puede ser de un tipo de datos + diferente. + +A continuación, creemos una lista que contiene un vector de números, caracteres, +una matriz, un marco de datos y otra lista: + +```{r list0, purl=TRUE} +l <- list(1:10, ## numeric + letters, ## character + installed.packages(), ## a matrix + cars, ## a data.frame + list(1, 2, 3)) ## a list +length(l) +str(l) +``` + +El subconjunto de listas se realiza usando `[]` para crear subconjuntos de una nueva sublista o `[[]]` +para extraer un solo elemento de esa lista (usando índices o nombres, si +la lista es nombrado). + +```{r, purl=TRUE} +l[[1]] ## first element +l[1:2] ## a list of length 2 +l[1] ## a list of length 1 +``` + +## Exportar y guardar datos tabulares {#sec:exportandsave} + +Hemos visto cómo leer una hoja de cálculo basada en texto en R usando la familia de funciones +`read.table`. Para exportar un `data.frame` a una +hoja de cálculo basada en texto, podemos usar el conjunto de funciones `write.table` +(`write.csv`, `write.delim`, ...). Todos toman la variable que se exportará +y el archivo al que se exportará. Por ejemplo, para exportar los datos +`rna` al archivo `my_rna.csv` en el directorio `data_output` +, ejecutaríamos: + +```{r, eval=FALSE, purl=TRUE} +write.csv(rna, file = "data_output/my_rna.csv") +``` + +This new csv file can now be shared with other collaborators who +aren't familiar with R. Note that even though there are commas in some of +the fields in the `data.frame` (see for example the "product" column), R will +by default surround each field with quotes, and thus we will be able to +read it back into R correctly, despite also using commas as column +separators. + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Datos tabulares en R + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/es/episodes/30-dplyr.Rmd b/locale/es/episodes/30-dplyr.Rmd new file mode 100644 index 000000000..652716022 --- /dev/null +++ b/locale/es/episodes/30-dplyr.Rmd @@ -0,0 +1,1047 @@ +--- +source: Rmd +title: Manipular y analizar datos con dplyr +teaching: 75 +exercises: 75 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Describe el propósito de los paquetes **`dplyr`** y **`tidyr`**. +- Describe varias de sus funciones que son extremadamente útiles para + manipular datos. +- Describa el concepto de formato de tabla ancho y largo, y vea + cómo remodelar un marco de datos de un formato a otro. +- Demuestre cómo unir tablas. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- Análisis de datos en R utilizando el metapaquete tidyverse + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +```{r loaddata_dplyr2, echo=FALSE, purl=FALSE, message=FALSE} +if (!file.exists("data/rnaseq.csv")) +download.file(url = "https://github.com/carpentries-incubator/bioc-intro/raw/main/episodes/data/rnaseq.csv", + destfile = "data/rnaseq.csv") +``` + +> Este episodio se basa en la lección _Análisis de datos y +> Visualización en R para ecologistas_ de Data Carpentries. + +## Manipulación de datos usando **`dplyr`** y **`tidyr`** + +El subconjunto de corchetes es útil, pero puede resultar engorroso y difícil de +leer, especialmente para operaciones complicadas. + +Algunos paquetes pueden facilitarnos mucho la tarea a la hora de manipular datos. +Los paquetes en R son básicamente conjuntos de funciones adicionales que te permiten +hacer más cosas. Las funciones que hemos estado usando hasta ahora, como `str()` o +`data.frame()`, vienen integradas en R; Cargar paquetes puede darle acceso a otras +funciones específicas. Antes de usar un paquete por primera vez, necesita instalarlo +en su máquina, y luego debe importarlo en cada sesión posterior de +R cuando lo necesite. + +- El paquete **`dplyr`** proporciona potentes herramientas para tareas de manipulación de datos. + Está diseñado para trabajar directamente con marcos de datos, con muchas tareas de manipulación + optimizadas. + +- Como veremos más adelante, a veces queremos remodelar un marco de datos para poder + hacer algunos análisis específicos o visualizarlo. El paquete **`tidyr`** aborda + este problema común de remodelar datos y proporciona herramientas para manipular + datos de forma ordenada. + +Para obtener más información sobre **`dplyr`** y **`tidyr`** después del taller, +quizás quieras consultar esta práctica transformación de datos con +\*\* +y este uno sobre +. + +- El paquete **`tidyverse`** es un "paquete general" que instala + varios paquetes útiles para el análisis de datos que funcionan bien juntos, + como **`tidyr`**, \* \*`dplyr`\*\*, **`ggplot2`**, **`tibble`**, etc. + Estos paquetes nos ayudan a trabajar e interactuar con los datos. + Nos permiten hacer muchas cosas con sus datos, como subconjuntos, transformaciones, + visualización, etc. + +Si realizó la configuración, ya debería haber instalado el paquete tidyverse. +Comprueba si lo tienes intentando cargarlo desde la biblioteca: + +```{r, message=FALSE, purl=TRUE} +## load the tidyverse packages, incl. dplyr +library("tidyverse") +``` + +Si recibió un mensaje de error `no hay ningún paquete llamado 'tidyverse'` entonces +aún no ha instalado el paquete para esta versión de R. Para instalar el tipo de paquete **`tidyverse`**: + +```{r, eval=FALSE, purl=TRUE} +BiocManager::install("tidyverse") +``` + +Si tuvo que instalar el paquete **`tidyverse`**, ¡no olvide cargarlo en esta sesión de R usando el comando `library()` arriba! + +## Cargando datos con tidyverse + +Instead of `read.csv()`, we will read in our data using the `read_csv()` +function (notice the `_` instead of the `.`), from the tidyverse2 package +**`readr`**. + +```{r, message=FALSE, purl=TRUE} +rna <- read_csv("data/rnaseq.csv") + +## view the data +rna +``` + +Observe que la clase de datos ahora se denomina "tibble". + +Tibbles modifica algunos de los comportamientos de los objetos del marco de datos que presentamos anteriormente en +. La estructura de datos es muy similar a un marco de datos. Para nuestros propósitos +las únicas diferencias son las siguientes: + +1. Muestra el tipo de datos de cada columna debajo de su nombre. + Tenga en cuenta que \<`dbl`\> es un tipo de datos definido para contener valores numéricos con + puntos decimales. + +2. Solo imprime las primeras filas de datos y solo tantas columnas como quepan en + una pantalla. + +Ahora vamos a aprender algunas de las funciones **`dplyr`** más comunes: + +- `select()`: subconjunto de columnas +- `filter()`: subconjunto de filas en condiciones +- `mutate()`: crea nuevas columnas usando información de otras columnas +- `group_by()` y `summarise()`: crean estadísticas resumidas sobre datos agrupados +- `arrange()`: ordenar resultados +- `count()`: cuenta valores discretos + +## Seleccionar columnas y filtrar filas + +Para seleccionar columnas de un marco de datos, use `select()`. El primer argumento +de esta función es el marco de datos (`rna`), y los argumentos +siguientes son las columnas que se deben conservar. + +```{r, purl=TRUE} +select(rna, gene, sample, tissue, expression) +``` + +Para seleccionar todas las columnas _excepto_ algunas, coloque un "-" delante de +la variable para excluirla. + +```{r, purl=TRUE} +select(rna, -tissue, -organism) +``` + +Esto seleccionará todas las variables en `rna` excepto `tejido` +y `organismo`. + +Para elegir filas según un criterio específico, utilice `filtro()`: + +```{r, purl=TRUE} +filter(rna, sex == "Male") +filter(rna, sex == "Male" & infection == "NonInfected") +``` + +Ahora imaginemos que estamos interesados en los homólogos humanos de los genes +de ratón analizados en este conjunto de datos. Esta información se puede encontrar en la +última columna del tibble `rna`, denominada +`hsapiens_homolog_associated_gene_name`. Para visualizarlo fácilmente, +crearemos una nueva tabla que contenga solo las 2 columnas `gene` y +`hsapiens_homolog_associated_gene_name`. + +```{r} +genes <- select(rna, gene, hsapiens_homolog_associated_gene_name) +genes +``` + +Algunos genes de ratón no tienen homólogos humanos. Estos se pueden recuperar usando +`filter()` y la función `is.na()`, que determina si +algo es un `NA`. + +```{r, purl=TRUE} +filter(genes, is.na(hsapiens_homolog_associated_gene_name)) +``` + +Si queremos conservar sólo genes de ratón que tienen un homólogo humano, podemos +insertar un "!" símbolo que niega el resultado, por lo que estamos pidiendo +cada fila donde hsapiens\_homolog\_associated\_gene\_name _no es_ un +`NA`. + +```{r, purl=TRUE} +filter(genes, !is.na(hsapiens_homolog_associated_gene_name)) +``` + +## Tubería + +¿Qué pasa si quieres seleccionar y filtrar al mismo tiempo? Hay tres +formas de hacer esto: usar pasos intermedios, funciones anidadas o canalizaciones. + +Con pasos intermedios, crea un marco de datos temporal y lo usa +como entrada para la siguiente función, como esta: + +```{r, purl=TRUE} +rna2 <- filter(rna, sex == "Male") +rna3 <- select(rna2, gene, sample, tissue, expression) +rna3 +``` + +Esto es legible, pero puede saturar tu espacio de trabajo con muchos +objetos intermedios que debes nombrar individualmente. Con múltiples +pasos, puede ser difícil seguirles la pista. + +También puedes anidar funciones (es decir, una función dentro de otra), +así: + +```{r, purl=TRUE} +rna3 <- select(filter(rna, sex == "Male"), gene, sample, tissue, expression) +rna3 +``` + +Esto es útil, pero puede ser difícil de leer si hay demasiadas funciones anidadas, ya que +R evalúa la expresión de adentro hacia afuera (en este caso, filtra y luego selecciona). + +La última opción, _pipes_, es una adición reciente a R. Pipes te permite tomar +la salida de una función y enviarla directamente a la siguiente, lo cual es útil +cuando necesitas hacer muchas cosas al mismo conjunto de datos. + +Las tuberías en R se parecen a `%>%` (disponible a través del paquete **`magrittr`** +) o `|>` (a través de la base R). If you use RStudio, you can type +the pipe with Ctrl + Shift + M if you +have a PC or Cmd + Shift + M if you +have a Mac. + +En el código anterior, usamos la tubería para enviar el conjunto de datos `rna` primero +a través de `filter()` para mantener las filas donde `sex` es Masculino, luego a través de +`select()` para mantener solo las columnas `gen`, `muestra`, `tejido` y +`expresión`. + +La tubería `%>%` toma el objeto a su izquierda y lo pasa directamente como +el primer argumento de la función a su derecha, no necesitamos +incluir explícitamente el marco de datos como un argumento para las funciones `filter()` y +`select()`. + +```{r, purl=TRUE} +rna %>% + filter(sex == "Male") %>% + select(gene, sample, tissue, expression) +``` + +A algunos les puede resultar útil leer la tubería como la palabra "entonces". Por ejemplo, +en el ejemplo anterior, tomamos el marco de datos `rna`, _luego_ `filtramos` +para filas con `sexo == "Masculino"`, _luego_ `seleccionamos` las columnas `gen`, `muestra`, +`tejido` y `expresión`. + +Las funciones **`dplyr`** por sí mismas son algo simples, pero al +combinarlas en flujos de trabajo lineales con la tubería, podemos lograr +manipulaciones más complejas de marcos de datos. + +Si queremos crear un nuevo objeto con esta versión más pequeña de los datos, +podemos asignarle un nuevo nombre: + +```{r, purl=TRUE} +rna3 <- rna %>% + filter(sex == "Male") %>% + select(gene, sample, tissue, expression) + +rna3 +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +Usando tuberías, subconjunto de datos de `rna` para mantener las observaciones en ratones hembra en el momento 0, +donde el gen tiene una expresión superior a 50000, y retenga solo las columnas +`gene`, `sample `, `tiempo`, `expresión` y `edad`. + +::::::::::::::: solution + +## Solución + +```{r} +rna %>% + filtro(expresión > 50000, + sexo == "Mujer", + tiempo == 0 ) %>% + seleccionar(gen, muestra , tiempo, expresión, edad) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Mudar + +Con frecuencia querrás crear nuevas columnas basadas en los valores de las columnas +existentes, por ejemplo, para hacer conversiones de unidades o para encontrar la proporción de valores en dos columnas +. Para esto usaremos `mutate()`. + +Para crear una nueva columna de tiempo en horas: + +```{r, purl=TRUE} +rna %>% + mutar(tiempo_horas = tiempo * 24) %>% + seleccionar(tiempo, tiempo_horas) +``` + +También puede crear una segunda columna nueva basada en la primera columna nueva dentro de la misma llamada de `mutate()`: + +```{r, purl=TRUE} +rna %>% + mutar(tiempo_horas = tiempo * 24, + tiempo_mn = tiempo_horas * 60) %>% + seleccionar(tiempo, tiempo_horas, tiempo_mn) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío + +Cree un nuevo marco de datos a partir de los datos `rna` que cumpla con los siguientes +criterios: contenga solo el `gen`, `chromosome_name`, +`phenotype_description`, `sample` y `expression`. columnas. Los valores de expresión +deben transformarse logarítmicamente. Este marco de datos +solo debe contener genes ubicados en los cromosomas sexuales, asociados con un +fenotipo\_descripción y con una expresión logarítmica superior a 5. + +**Sugerencia**: piense en cómo se deben ordenar los comandos para producir +este marco de datos. + +::::::::::::::: solution + +## Solución + +```{r, eval=TRUE, purl=TRUE} +rna %>% + mutate(expression = log(expression)) %>% + select(gene, chromosome_name, phenotype_description, sample, expression) %>% + filter(chromosome_name == "X" | chromosome_name == "Y") %>% + filter(!is.na(phenotype_description)) %>% + filter(expression > 5) +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## Análisis de datos divididos, aplicados y combinados + +Muchas tareas de análisis de datos se pueden abordar utilizando el paradigma +_split-apply-combine_: divida los datos en grupos, aplique algún análisis +a cada grupo y luego combine los resultados. **`dplyr`** +hace que esto sea muy fácil mediante el uso de la función `group_by()`. + +```{r} +arn %>% + group_by(gen) +``` + +La función `group_by()` no realiza ningún procesamiento de datos, +agrupa los datos en subconjuntos: en el ejemplo anterior, nuestro +`tibble` inicial de `r nrow(rna)` Las observaciones se dividen en grupos +`r length(unique(rna$gene))` según la variable `gen`. + +De manera similar, podríamos decidir agrupar el tibble por muestras: + +```{r} +rna %>% + group_by(muestra) +``` + +Aquí nuestro `tibble` inicial de observaciones de `r nrow(rna)` se divide en +`r length(unique(rna$sample))` grupos basados en la variable `sample`. + +Una vez agrupados los datos, las operaciones posteriores se aplicarán +en cada grupo de forma independiente. + +### La función `resumir()` + +`group_by()` se usa a menudo junto con `summarise()`, que +colapsa cada grupo en un resumen de una sola fila de ese grupo. + +`group_by()` toma como argumentos los nombres de las columnas que contienen las variables +**categóricas** para las que desea calcular el resumen de estadísticas +. Entonces, para calcular la "expresión" media por gen: + +```{r} +rna %>% + group_by(gen) %>% + resumen(expresión_media = media(expresión)) +``` + +También podríamos querer calcular los niveles medios de expresión de todos los genes en cada muestra: + +```{r} +rna %>% + group_by(muestra) %>% + resumen(expresión_media = media(expresión)) +``` + +Pero también podemos agrupar por varias columnas: + +```{r} +rna %>% + group_by(gen, infección, tiempo) %>% + resumen(expresión_media = media(expresión)) +``` + +Una vez agrupados los datos, también puede resumir varias variables al mismo tiempo +(y no necesariamente en la misma variable). Por ejemplo, podríamos agregar una columna +que indique la `expresión` mediana por gen y por condición: + +```{r, purl=TRUE} +rna %>% + group_by(gen, infección, tiempo) %>% + resumen(expresión_media = media (expresión), + expresión_mediana = mediana (expresión)) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío + +Calcule el nivel de expresión medio del gen "Dok3" por puntos de tiempo. + +::::::::::::::: solution + +## Solución + +```{r, purl=TRUE} +rna %>% + filter(gen == "Dok3") %>% + group_by(time) %>% + resumen(media = media(expresión)) +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +### Contando + +Cuando trabajamos con datos, a menudo queremos saber el número de observaciones encontradas +para cada factor o combinación de factores. Para esta tarea, **`dplyr`** proporciona +`count()`. Por ejemplo, si quisiéramos contar el número de filas de datos para +cada muestra infectada y no infectada, haríamos: + +```{r, purl=TRUE} +ARN %>% + recuento(infección) +``` + +La función `count()` es una abreviatura de algo que ya hemos visto: agrupar por una variable y resumirla contando el número de observaciones en ese grupo. En otras palabras, `rna %>% count(infection)` es equivalente a: + +```{r, purl=TRUE} +rna %>% + group_by(infección) %>% + resumen(n = n()) +``` + +El ejemplo anterior muestra el uso de `count()` para contar el número de filas/observaciones +para _un_ factor (es decir, `infección`). +Si quisiéramos contar una _combinación de factores_, como `infección` y `tiempo`, +especificaríamos el primer y el segundo factor como argumentos de `count()`: + +```{r, purl=TRUE} +rna %>% + recuento(infección, tiempo) +``` + +que es equivalente a esto: + +```{r, purl=TRUE} +rna %>% + group_by(infección, tiempo) %>% + resumen(n = n()) +``` + +A veces resulta útil ordenar el resultado para facilitar las comparaciones. +Podemos usar `arrange()` para ordenar la tabla. +Por ejemplo, es posible que deseemos organizar la tabla anterior por tiempo: + +```{r, purl=TRUE} +rna %>% + recuento(infección, tiempo) %>% + organizar(tiempo) +``` + +o por conteos: + +```{r, purl=TRUE} +rna %>% + recuento(infección, tiempo) %>% + organizar(n) +``` + +Para ordenar en orden descendente, necesitamos agregar la función `desc()`: + +```{r, purl=TRUE} +rna %>% + recuento(infección, tiempo) %>% + organizar(desc(n)) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío + +1. ¿Cuántos genes se analizaron en cada muestra? +2. Utilice `group_by()` y `summarise()` para evaluar la profundidad de secuenciación (la suma de todos los recuentos) en cada muestra. ¿Qué muestra tiene la mayor profundidad de secuenciación? +3. Elija una muestra y evalúe la cantidad de genes por biotipo. +4. Identifique los genes asociados con la descripción del fenotipo de "metilación anormal del ADN" y calcule su expresión media (en log) en el tiempo 0, el tiempo 4 y el tiempo 8. + +::::::::::::::: solution + +## Solución + +```{r} +## 1. +rna %>% + count(sample) +## 2. +rna %>% + group_by(sample) %>% + summarise(seq_depth = sum(expression)) %>% + arrange(desc(seq_depth)) +## 3. +rna %>% + filter(sample == "GSM2545336") %>% + count(gene_biotype) %>% + arrange(desc(n)) +## 4. +rna %>% + filter(phenotype_description == "abnormal DNA methylation") %>% + group_by(gene, time) %>% + summarise(mean_expression = mean(log(expression))) %>% + arrange() +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## Reformar datos + +En el tibble `rna`, las filas contienen valores de expresión (la unidad) que están +asociados con una combinación de otras 2 variables: `gen` y `sample`. + +Todas las demás columnas corresponden a variables que describen +la muestra (organismo, edad, sexo, ...) o el gen (gen\_biotipo, ENTREZ\_ID, producto, ...). +Las variables que no cambian con genes o con muestras tendrán el mismo valor en todas las filas. + +```{r} +rna %>% + organizar(gen) +``` + +Esta estructura se denomina "formato largo", ya que una columna contiene todos los valores, +y otras columnas enumeran el contexto del valor. + +En ciertos casos, el "formato largo" no es realmente "legible para humanos", y se prefiere otro formato, +un "formato ancho", como una forma más compacta de representar los datos. +Este suele ser el caso de los valores de expresión genética que los científicos están acostumbrados a considerar +como matrices, donde las filas representan genes y las columnas representan muestras. + +En este formato, por lo tanto, sería sencillo +explorar la relación entre los niveles de expresión genética dentro y +entre las muestras. + +```{r, echo=FALSE} +rna %>% + select(gen, muestra, expresión) %>% + pivot_wider(nombres_de = muestra, + valores_de = expresión) +``` + +Para convertir los valores de expresión genética de `rna` a un formato amplio, +, necesitamos crear una nueva tabla donde los valores de la columna `muestra` +se conviertan en los nombres de las variables de la columna. + +The key point here is that we are still following +a tidy data structure, but we have **reshaped** the data according to +the observations of interest: expression levels per gene instead +of recording them per gene and per sample. + +La transformación opuesta sería transformar los nombres de las columnas en +valores de una nueva variable. + +Podemos hacer ambas transformaciones con dos funciones `tidyr`, +`pivot_longer()` y `pivot_wider()` (ver +[aquí](https://tidyr.tidyverse.org /dev/articles/pivot.html) para +detalles). + +### Pivotar los datos a un formato más amplio + +Seleccionemos las primeras 3 columnas de `rna` y usemos `pivot_wider()` +para transformar los datos a un formato amplio. + +```{r, purl=TRUE} +rna_exp <- rna %>% + select(gen, muestra, expresión) +rna_exp +``` + +`pivot_wider` toma tres argumentos principales: + +1. los datos a transformar; +2. `names_from`: la columna cuyos valores se convertirán en la nueva columna + nombres; +3. `values_from`: la columna cuyos valores llenarán las nuevas columnas + . + +```{r, fig.cap="Pivote amplio de los datos `rna`.", echo=FALSE, message=FALSE} +knitr::include_graphics("fig/pivot_wider.png") + +``` + +```{r, purl=TRUE} +rna_wide <- rna_exp %>% + pivot_wider(names_from = sample, + values_from = expression) +rna_wide +``` + +Tenga en cuenta que, de forma predeterminada, la función `pivot_wider()` agregará `NA` para los valores faltantes. + +Imaginemos que, por alguna razón, nos faltan algunos valores de expresión para algunos genes +en ciertas muestras. En el siguiente ejemplo ficticio, el gen Cyp2d22 tiene solo +un valor de expresión, en la muestra GSM2545338. + +```{r, purl=TRUE} +rna_with_missing_values <- rna %>% + select(gene, sample, expression) %>% + filter(gene %in% c("Asl", "Apod", "Cyp2d22")) %>% + filter(sample %in% c("GSM2545336", "GSM2545337", "GSM2545338")) %>% + arrange(sample) %>% + filter(!(gene == "Cyp2d22" & sample != "GSM2545338")) +rna_with_missing_values +``` + +De forma predeterminada, la función `pivot_wider()` agregará `NA` para los valores +faltantes. Esto se puede parametrizar con el argumento `values_fill` de +la función `pivot_wider()`. + +```{r, purl=TRUE} +rna_with_missing_values %>% + pivot_wider(nombres_de = muestra, + valores_de = expresión) + +rna_with_missing_values %>% + pivot_wider(nombres_de = muestra, + valores_de = expresión, + valores_relleno = 0) +``` + +### Pivotar datos a un formato más largo + +En la situación opuesta, usamos los nombres de las columnas y los convertimos en +un par de nuevas variables. Una variable representa los nombres de las columnas como valores +y la otra variable contiene los valores previamente +asociados con los nombres de las columnas. + +`pivot_longer()` toma cuatro argumentos principales: + +1. los datos a transformar; +2. `names_to`: el nuevo nombre de la columna que deseamos crear y completar con los + nombres de las columnas actuales; +3. `values_to`: el nuevo nombre de la columna que deseamos crear y completar con + valores actuales; +4. los nombres de las columnas que se utilizarán para completar las variables `names_to` y + `values_to` (o para eliminar). + +```{r, fig.cap="Pivote largo de los datos `rna`.", echo=FALSE, message=FALSE} +knitr::include_graphics("fig/pivot_longer.png") + +``` + +To recreate `rna_long` from `rna_wide` we would create a key +called `sample` and value called `expression` and use all columns +except `gene` for the key variable. Here we drop `gene` column +with a minus sign. + +Notice how the new variable names are to be quoted here. + +```{r} +rna_long <- rna_wide %>% + pivot_longer(names_to = "sample", + values_to = "expression", + -gene) +rna_long +``` + +También podríamos haber usado una especificación sobre qué columnas incluir +. Esto puede ser útil si tiene una gran cantidad de columnas de identificación +, y es más fácil especificar qué recopilar que qué dejar +solo. Aquí, la función `starts_with()` puede ayudar a recuperar +nombres de muestra sin tener que enumerarlos todos. +¡Otra posibilidad sería utilizar el operador `:`! + +```{r} +rna_wide %>% + pivot_longer(names_to = "muestra", + valores_to = "expresión", + cols = comienza_con("GSM")) +rna_wide %> % + pivot_longer(names_to = "muestra", + valores_to = "expresión", + GSM2545336:GSM2545380) +``` + +Tenga en cuenta que si nos faltaran valores en el formato ancho, `NA` estaría +incluido en el nuevo formato largo. + +Recuerde nuestro tibble ficticio anterior que contiene valores faltantes: + +```{r} +rna_with_missing_values + +wide_with_NA <- rna_with_missing_values %>% + pivot_wider(names_from = sample, + values_from = expression) +wide_with_NA + +wide_with_NA %>% + pivot_longer(names_to = "sample", + values_to = "expression", + -gene) +``` + +Pasar a formatos más amplios y largos puede ser una forma útil de equilibrar un conjunto de datos +para que cada réplica tenga la misma composición. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Pregunta + +A partir de la tabla de ARN, utilice la función `pivot_wider()` para crear +una tabla de formato amplio que proporcione los niveles de expresión genética en cada ratón. +Luego use la función `pivot_longer()` para restaurar una tabla de formato largo. + +::::::::::::::: solution + +## Solución + +```{r, answer=TRUE, purl=TRUE} +rna1 <- rna %>% +select(gen, ratón, expresión) %>% +pivot_wider(names_from = ratón, valores_from = expresión) +rna1 + +rna1 %>% +pivot_longer(names_to = "mouse_id", valores_to = "cuentas", -gene) +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Pregunta + +Subconjunto de genes ubicados en los cromosomas X e Y del marco de datos `rna` y +distribuyen el marco de datos con `sexo` como columnas, `cromosoma_nombre` como +filas y la expresión media de los genes ubicados en cada cromosoma como los valores, +como en el siguiente tibble: + +```{r, echo=FALSE, message=FALSE} +knitr::include_graphics("fig/Exercise_pivot_W.png") +``` + +¡Necesitará resumir antes de remodelar! + +::::::::::::::: solution + +## Solución + +Primero calculemos el nivel de expresión medio de los genes ligados a X e Y de +muestras masculinas y femeninas... + +```{r} + arn %>% + filtro(nombre_cromosoma == "Y" | nombre_cromosoma == "X") %>% + grupo_por(sexo, nombre_cromosoma) %>% + resumen(media = media (expresión)) +``` + +Y gire la tabla a formato ancho + +```{r, answer=TRUE, purl=TRUE} +rna_1 <- arn %>% + filter(nombre_cromosoma == "Y" | nombre_cromosoma == "X") %>% + group_by(sexo, nombre_cromosoma) %>% + resumir (media = media (expresión)) %>% + pivot_wider(nombres_de = sexo, + valores_de = media) + +rna_1 +``` + +Ahora tome ese marco de datos y transfórmelo con `pivot_longer()` para que +cada fila sea un `cromosoma_nombre` único por combinación de `género`. + +```{r, answer=TRUE, purl=TRUE} +rna_1 %>% + pivot_longer(names_to = "género", + valores_to = "media", + -chromosome_name) + +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Pregunta + +Utilice el conjunto de datos `rna` para crear una matriz de expresión donde cada fila +represente los niveles de expresión medios de genes y las columnas representen +los diferentes puntos de tiempo. + +::::::::::::::: solution + +## Solución + +Primero calculemos la expresión media por gen y por tiempo. + +```{r} +rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) +``` + +antes de usar la función pivot\_wider() + +```{r} +rna_time <- rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) +rna_time +``` + +Observe que esto genera un tibble con algunos nombres de columnas que comienzan con un número. +Si quisiéramos seleccionar la columna correspondiente a los puntos de tiempo, +no podríamos usar los nombres de las columnas directamente... ¿Qué pasa cuando seleccionamos la columna 4? + +```{r} +rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) %>% + select(gene, 4) +``` + +Para seleccionar el punto de tiempo 4, tendríamos que citar el nombre de la columna, con comillas invertidas "\\`" + +```{r} +rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) %>% + select(gene, `4`) +``` + +Otra posibilidad sería cambiar el nombre de la columna, +eligiendo un nombre que no comience con un número: + +```{r} +rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) %>% + rename("time0" = `0`, "time4" = `4`, "time8" = `8`) %>% + select(gene, time4) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Pregunta + +Utilice el marco de datos anterior que contiene los niveles de expresión medios por punto de tiempo y cree +una nueva columna que contenga los cambios de pliegue entre el punto de tiempo 8 y el punto de tiempo 0, y los cambios de pliegue +entre el punto de tiempo 8 y el punto de tiempo 4. +Convierta esta tabla en una tabla de formato largo que recopile los cambios de pliegue calculados. + +::::::::::::::: solution + +## Solución + +A partir del tibble rna\_time: + +```{r} +rna_time +``` + +Calcular cambios de pliegue: + +```{r} +rna_time %>% + mutate(time_8_vs_0 = `8` / `0`, time_8_vs_4 = `8` / `4`) +``` + +Y use la función pivot\_longer(): + +```{r} +rna_time %>% + mutate(time_8_vs_0 = `8` / `0`, time_8_vs_4 = `8` / `4`) %>% + pivot_longer(names_to = "comparisons", + values_to = "Fold_changes", + time_8_vs_0:time_8_vs_4) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Unir mesas + +En muchas situaciones de la vida real, los datos se distribuyen en varias tablas. +Por lo general, esto ocurre porque se recopilan +diferentes tipos de información de diferentes fuentes. + +Puede ser deseable que algunos análisis combinen datos de dos o más tablas +en un solo marco de datos basado en una columna que sería común +a todas las tablas. + +El paquete `dplyr` proporciona un conjunto de funciones de unión para combinar dos marcos de datos +basados en coincidencias dentro de columnas especificadas. Aquí, +proporcionamos una breve introducción a las uniones. Para obtener más información, +consulte el capítulo sobre [tabla +uniones] (https://uclouvain-cbio.github.io/WSBIM1207/sec-join.html). La +Hoja de trucos de transformación de datos + +también proporciona una breve descripción general en las uniones de la mesa. + +Vamos a ilustrar la unión usando una pequeña tabla, `rna_mini` que +crearemos subconjuntos de la tabla `rna` original, manteniendo solo 3 +columnas y 10 líneas. + +```{r} +rna_mini <- rna %>% + select(gene, sample, expression) %>% + head(10) +rna_mini +``` + +La segunda tabla, `annot1`, contiene 2 columnas, gene y +gene\_description. Puede +[descargar annot1.csv](https://carpentries-incubator.github.io/bioc-intro/data/annot1.csv) +haciendo clic en el enlace y luego moviéndose a la carpeta `data/`, o +puedes usar el código R a continuación para descargarlo directamente a la carpeta. + +```{r, message=FALSE} +download.file(url = "https://carpentries-incubator.github.io/bioc-intro/data/annot1.csv", + destfile = "data/annot1.csv") +annot1 <- read_csv(file = "data/annot1.csv") +annot1 +``` + +Ahora queremos unir estas dos tablas en una sola que contenga todas las variables +usando la función `full_join()` del paquete `dplyr`. La función +encontrará automáticamente la variable común que coincida con las columnas +de la primera y segunda tabla. En este caso, "gen" es la variable +común. Estas variables se denominan claves. Las claves se utilizan para hacer coincidir +observaciones en diferentes tablas. + +```{r} +full_join(rna_mini, annot1) +``` + +En la vida real, las anotaciones genéticas a veces se etiquetan de manera diferente. + +La tabla `annot2` es exactamente igual que `annot1` excepto que la variable +que contiene los nombres de los genes está etiquetada de manera diferente. Nuevamente, +[descarga annot2.csv](https://carpentries-incubator.github.io/bioc-intro/data/annot2.csv) +tú mismo y muévelo a `data/ `o use el código R a continuación. + +```{r, message=FALSE} +download.file(url = "https://carpentries-incubator.github.io/bioc-intro/data/annot2.csv", + destfile = "data/annot2.csv") +annot2 <- read_csv(file = "data/annot2.csv") +annot2 +``` + +En caso de que ninguno de los nombres de las variables coincida, podemos configurar manualmente las +variables que se utilizarán para la coincidencia. Estas variables se pueden configurar usando +el argumento `by`, como se muestra a continuación con las tablas `rna_mini` y `annot2`. + +```{r} +full_join(rna_mini, annot2, by = c("gene" = "external_gene_name")) +``` + +Como se puede ver arriba, el nombre de la variable de la primera tabla se conserva +en la unida. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío: + +Descargue la tabla `annot3` haciendo clic +[aquí](https://carpentries-incubator.github.io/bioc-intro/data/annot3.csv) +y coloque la tabla en su repositorio de datos. Usando la función `full_join()` +, une las tablas `rna_mini` y `annot3`. ¿Qué ha sucedido con los +genes _Klk6_, _mt-Tf_, _mt-Rnr1_, _mt-Tv_, _mt-Rnr2_ y _mt-Tl1_? + +::::::::::::::: solution + +## Solución + +```{r, message=FALSE} +annot3 <- read_csv("data/annot3.csv") +full_join(rna_mini, annot3) +``` + +Los genes _Klk6_ solo están presentes en `rna_mini`, mientras que los genes _mt-Tf_, _mt-Rnr1_, _mt-Tv_, +_mt-Rnr2_ y _mt-Tl1_ están solo está presente en la tabla `annot3`. Sus valores respectivos para las variables +de la tabla se han codificado como faltantes. + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Exportar datos + +Ahora que ha aprendido a utilizar `dplyr` para extraer información de +o resumir sus datos sin procesar, es posible que desee exportar estos nuevos conjuntos de datos para compartirlos +con sus colaboradores o para archivarlos. + +Similar a la función `read_csv()` utilizada para leer archivos CSV en R, existe +una función `write_csv()` que genera archivos CSV a partir de marcos de datos. + +Antes de usar `write_csv()`, vamos a crear una nueva carpeta, `data_output`, +en nuestro directorio de trabajo que almacenará este conjunto de datos generado. No queremos que +escriba conjuntos de datos generados en el mismo directorio que nuestros datos sin procesar. +Es una buena práctica mantenerlos separados. La carpeta `data` solo debe contener +los datos sin procesar y sin modificar, y debe dejarse en paz para asegurarnos de que no los eliminemos +ni los modifiquemos. Por el contrario, nuestro script generará el contenido del directorio `data_output` +, por lo que incluso si los archivos que contiene se eliminan, siempre podemos +volver a generarlos. + +Usemos `write_csv()` para guardar la tabla rna\_wide que hemos creado anteriormente. + +```{r, purl=TRUE, eval=FALSE} +write_csv(rna_wide, file = "data_output/rna_wide.csv") +``` + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Datos tabulares en R usando el metapaquete tidyverse + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/es/episodes/40-visualization.Rmd b/locale/es/episodes/40-visualization.Rmd new file mode 100644 index 000000000..904cc3ddc --- /dev/null +++ b/locale/es/episodes/40-visualization.Rmd @@ -0,0 +1,1107 @@ +--- +source: Rmd +title: Visualización de datos +teaching: 60 +exercises: 60 +--- + +```{r loaddata_vis, echo=FALSE, purl=FALSE, message=FALSE} +if (!file.exists("data/rnaseq.csv")) +download.file(url = "https://github.com/carpentries-incubator/bioc-intro/raw/main/episodes/data/rnaseq.csv", + destfile = "data/rnaseq.csv") +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Produzca diagramas de dispersión, diagramas de caja, diagramas de líneas, etc. utilizando ggplot. +- Establezca configuraciones de trama universales. +- Describe qué es el facetado y aplícalo en ggplot. +- Modifique la estética de un gráfico ggplot existente (incluidas las etiquetas de los ejes y el color). +- Cree gráficos complejos y personalizados a partir de datos en un marco de datos. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- Visualización en R + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +```{r vis_setup, echo=FALSE} +rna <- read.csv("data/rnaseq.csv") +``` + +> Este episodio se basa en la lección _Análisis de datos y +> Visualización en R para ecologistas_ de Data Carpentries. + +## Visualización de datos + +Comenzamos cargando los paquetes requeridos. **`ggplot2`** está incluido en +el paquete **`tidyverse`**. + +```{r load-package, message=FALSE, purl=TRUE} +library("tidyverse") +``` + +Si aún no está en el espacio de trabajo, cargue los datos que guardamos en la lección +anterior. + +```{r load-data, eval=FALSE, purl=TRUE} +rna <- read.csv("data/rnaseq.csv") +``` + +La Hoja de trucos de visualización de datos + +cubrirá los conceptos básicos y las funciones más avanzadas de ` ggplot2` y +ayudará, además de servir como recordatorio, a obtener una descripción general de las +muchas representaciones de datos disponibles en el paquete. Los siguientes videos +tutoriales ([parte 1](https://www.youtube.com/watch?v=h29g21z0a68) y +[2](https://www.youtube.com /watch?v=0m4yywqNPVY)) de Thomas Lin Pedersen +también son muy instructivos. + +## Trazar con `ggplot2` + +`ggplot2` es un paquete de trazado que simplifica la creación de trazados +complejos a partir de datos en un marco de datos. Proporciona una interfaz +más programática para especificar qué variables trazar, cómo se muestran, +y propiedades visuales generales. El fundamento teórico que sustenta +el `ggplot2` es la _Gramática de Gráficos_ (@Wilkinson:2005). Usando este enfoque +, solo necesitamos cambios mínimos si los datos subyacentes cambian o +si decidimos cambiar de un diagrama de barras a un diagrama de dispersión. Esto ayuda a +a crear gráficos con calidad de publicación con una cantidad mínima de ajustes +y ajustes. + +Hay un libro sobre `ggplot2` (@ggplot2book) que proporciona una buena +descripción general, pero está desactualizado. La tercera edición está en preparación y +estará [disponible gratuitamente en línea](https://ggplot2-book.org/). La página web `ggplot2` +([https://ggplot2.tidyverse.org](https://ggplot2.tidyverse.org)) proporciona amplia documentación. + +`ggplot2` funciona como datos en formato 'largo', es decir, una columna para +cada dimensión y una fila para cada observación. Los datos bien estructurados +te ahorrarán mucho tiempo al hacer figuras con `ggplot2`. + +Los gráficos de ggplot se crean paso a paso agregando nuevos elementos. Agregar +capas de esta manera permite una gran flexibilidad y +personalización de los gráficos. + +> La idea detrás de la Gramática de Gráficos es que puedes construir cada gráfico +> a partir de los mismos 3 componentes: (1) un conjunto de datos, (2) un sistema de coordenadas, +> y (3) geoms. — es decir, marcas visuales que representan puntos de datos \[^tres\\_comp\\_ggplot2] + +[^three_comp_ggplot2]: Fuente: [Hoja de referencia de visualización de datos](https://raw.githubusercontent.com/rstudio/cheatsheets/main/data-visualization.pdf). + +Para construir un ggplot, usaremos la siguiente plantilla básica que se puede +usar para diferentes tipos de gráficos: + +``` +ggplot(data = , mapping = aes()) + () +``` + +- use la función `ggplot()` y vincule el gráfico a un \*\*marco de datos + \*\* específico usando el argumento `data` + +```{r, eval=FALSE} +ggplot(data = rna) +``` + +- defina un **mapeo** (usando la función estética (`aes`)), seleccionando + las variables que se trazarán y especificando cómo presentarlas + en el gráfico, por ejemplo, como x/ y posiciones o características como + tamaño, forma, color, etc. + +```{r, eval=FALSE} +ggplot(data = rna, mapping = aes(x = expression)) +``` + +- agregue '**geoms**': geometrías o representaciones gráficas de los datos + en el gráfico (puntos, líneas, barras). `ggplot2` ofrece muchas + geoms diferentes; Usaremos algunos comunes hoy, que incluyen: + + ``` + * `geom_point()` para diagramas de dispersión, diagramas de puntos, etc. + * `geom_histogram()` para histogramas + * `geom_boxplot()` para, bueno, diagramas de caja. + * `geom_line()` para líneas de tendencia, series de tiempo, etc. + ``` + +Para agregar una geometría (etry) al gráfico, use el operador `+`. Usemos +`geom_histogram()` primero: + +```{r first-ggplot, cache=FALSE, purl=TRUE} +ggplot(data = rna, mapping = aes(x = expression)) + + geom_histogram() +``` + +El `+` en el paquete `ggplot2` es particularmente útil porque +te permite modificar objetos `ggplot` existentes. Esto significa que puedes +configurar fácilmente plantillas de gráficos y explorar cómodamente diferentes tipos de gráficos +, por lo que el gráfico anterior también se puede generar con un código como este: + +```{r, eval=FALSE, purl=TRUE} +# Asignar gráfico a una variable +rna_plot <- ggplot(data = rna, + mapping = aes(x = expression)) + +# Dibujar el gráfico +rna_plot + geom_histogram() +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío + +Probablemente hayas notado un mensaje automático que aparece cuando +dibuja el histograma: + +```{r, echo=FALSE, fig.show="hide"} +ggplot(rna, aes(x = expression)) + + geom_histogram() +``` + +Cambie los argumentos `bins` o `binwidth` de `geom_histogram()` a +cambie el número o ancho de los bins. + +::::::::::::::: solution + +## Solución + +```{r, purl=TRUE} +# cambiar contenedores +ggplot(rna, aes(x = expresión)) + + geom_histogram(bins = 15) + +# cambiar ancho de contenedor +ggplot(rna, aes( x = expresión)) + + geom_histogram(binwidth = 2000) +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +Podemos observar aquí que los datos están sesgados hacia la derecha. Podemos aplicar la transformación +log2 para tener una distribución más simétrica. Tenga en cuenta que +agregamos aquí un pequeño valor constante (`+1`) para evitar que se devuelvan valores `-Inf` +para valores de expresión iguales a 0. + +```{r log-transfo, cache=FALSE, purl=TRUE} +rna <- rna %>% + mutar(expresión_log = log2(expresión + 1)) +``` + +Si ahora dibujamos el histograma de las expresiones transformadas log2, la distribución +está más cerca de una distribución normal. + +```{r second-ggplot, cache=FALSE, purl=TRUE} +ggplot(rna, aes(x = expresión_log)) + geom_histogram() +``` + +De ahora en adelante trabajaremos en los valores de expresión transformados logarítmicamente. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío + +Otra forma de visualizar esta transformación es considerar la escala +de las observaciones. Por ejemplo, puede que valga la pena cambiar la escala +del eje para distribuir mejor las observaciones en el espacio del gráfico +. Cambiar la escala de los ejes se realiza de manera similar a +agregar/modificar otros componentes (es decir, agregando incrementalmente comandos +). Intenta hacer esta modificación: + +- Representa la expresión no transformada en la escala log10; ver + `scale_x_log10()`. Compáralo con el gráfico anterior. ¿Por qué + ahora aparecen mensajes de advertencia? + +::::::::::::::: solución + +## Solución + +```{r, eval=TRUE, purl=TRUE, echo=TRUE} +ggplot(datos = rna,mapping = aes(x = expresión))+ + geom_histogram() + + scale_x_log10() +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +**Notas** + +- Todo lo que pongas en la función `ggplot()` puede ser visto por cualquier geom + capas que agregues (es decir, estas son configuraciones de trazado globales). Este + incluye el mapeo de los ejes x e y que configuró en `aes()`. +- También puede especificar asignaciones para una geom determinada independientemente de las + asignaciones definidas globalmente en la función `ggplot()`. +- El signo `+` usado para agregar nuevas capas debe colocarse al final de la línea + que contiene la capa _anterior_. If, instead, the `+` sign is + added at the beginning of the line containing the new layer, + `ggplot2` will not add the new layer and will return an error + message. + +```{r, eval=FALSE} +# This is the correct syntax for adding layers +rna_plot + + geom_histogram() + +# This will not add the new layer and will return an error message +rna_plot + + geom_histogram() +``` + +## Construyendo sus parcelas de forma iterativa + +Ahora dibujaremos un diagrama de dispersión con dos variables continuas y la función +`geom_point()`. Este gráfico representará los cambios log2 +de la expresión que compara el tiempo 8 con el tiempo 0 y el tiempo 4 con el tiempo 0. +Para este fin, primero necesitamos calcular las medias de los valores de expresión +transformados logarítmicamente por gen y tiempo, luego el pliegue logarítmico cambia +restando las expresiones logarítmicas medias entre el tiempo 8 y el tiempo 0. y +entre el tiempo 4 y el tiempo 0. Tenga en cuenta que también incluimos aquí el biotipo del gen +que usaremos más adelante para representar los genes. Guardaremos +los cambios de pliegue en un nuevo marco de datos llamado `rna_fc.` + +```{r rna_fc, cache=FALSE, purl=TRUE} +rna_fc <- rna %>% seleccionar(gen, tiempo, + biotipo_gen, registro_expresión) %>% + group_by(gen, tiempo, biotipo_gen) %>% + resumir(exp_media = mean(expression_log)) %>% + pivot_wider(names_from = tiempo, + valores_from = mean_exp) %>% + mutate(time_8_vs_0 = `8` - `0`, time_4_vs_0 = `4` - `0`) + +``` + +Luego podemos construir un ggplot con el conjunto de datos recién creado `rna_fc`. +La construcción de parcelas con `ggplot2` suele ser un proceso iterativo. +comenzamos definiendo el conjunto de datos que usaremos, diseñamos los ejes y elegimos una geom +: + +```{r create-ggplot-object, cache=FALSE, purl=TRUE} +ggplot(datos = rna_fc, mapeo = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point() +``` + +Luego, comenzamos a modificar este gráfico para extraer más información del mismo. +Por ejemplo, podemos agregar transparencia (`alfa`) para evitar el trazado excesivo: + +```{r adding-transparency, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapeo = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point(alpha = 0.3) +``` + +También podemos agregar colores para todos los puntos: + +```{r adding-colors, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapeo = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point(alpha = 0.3, color = "azul") +``` + +O para colorear cada gen en el gráfico de manera diferente, puede usar un vector como +una entrada para el argumento **color**. `ggplot2` proporcionará un color +diferente correspondiente a diferentes valores en el vector. Aquí hay un +ejemplo donde coloreamos con `gene_biotype`: + +```{r color-by-gene_biotype1, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapeo = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point(alpha = 0.3, aes(color = gene_biotype)) + +``` + +También podemos especificar los colores directamente dentro del mapeo proporcionado en +la función `ggplot()`. Esto será visto por cualquier capa de geom y el mapeo +estará determinado por los ejes x e y configurados en `aes()`. + +```{r color-by-gene_biotype2, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapeo = aes(x = time_4_vs_0, y = time_8_vs_0, + color = gene_biotype)) + + geom_point(alpha = 0.3) +``` + +Finalmente, también podríamos agregar una línea diagonal con la función `geom_abline()` +: + +```{r adding-diag, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapeo = aes(x = time_4_vs_0, y = time_8_vs_0, + color = gene_biotype)) + + geom_point(alpha = 0.3) + + geom_abline(intercept = 0) +``` + +Tenga en cuenta que podemos cambiar la capa geom de `geom_point` a +`geom_jitter` y los colores seguirán estando determinados por `gene_biotype`. + +```{r color-by-gene_biotype3, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapeo = aes(x = time_4_vs_0, y = time_8_vs_0, + color = gene_biotype)) + + geom_jitter(alpha = 0.3) + + geom_abline(intercept = 0) +``` + +```{r, echo=FALSE, message=FALSE} +biblioteca("hexbin") +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío + +Los diagramas de dispersión pueden ser herramientas exploratorias útiles para conjuntos de datos pequeños. Para +conjuntos de datos con una gran cantidad de observaciones, como el conjunto de datos `rna_fc` +, el trazado excesivo de puntos puede ser una limitación de los diagramas de dispersión. +Una estrategia para manejar tales configuraciones es utilizar agrupación hexagonal de +observaciones. El espacio de la trama está teselado en hexágonos. A cada hexágono +se le asigna un color según el número de observaciones que +caen dentro de sus límites. + +- Para utilizar la agrupación hexagonal en `ggplot2`, primero instale el paquete R + `hexbin` de CRAN y cárguelo. + +- Luego use la función `geom_hex()` para producir la figura hexbin. + +- ¿Cuáles son las fortalezas y debilidades relativas de un diagrama de bin hexagonal + en comparación con un diagrama de dispersión? Examine el diagrama de dispersión anterior + y compárelo con el diagrama de bin hexagonal que creó. + +::::::::::::::: solución + +## Solución + +```{r, eval=FALSE, purl=TRUE} +instalar.paquetes("hexbin") +``` + +```{r, purl=TRUE} +biblioteca("hexbin") + +ggplot(data = rna_fc, mapeo = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_hex() + + geom_abline(intercepción = 0 ) + +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío + +Utilice lo que acaba de aprender para crear un diagrama de dispersión de `expression_log` +sobre `sample` del conjunto de datos `rna` con el tiempo mostrado en +colores diferentes. ¿Es esta una buena manera de mostrar este tipo de datos? + +::::::::::::::: solución + +## Solución + +```{r, eval=TRUE, purl=TRUE} +ggplot(datos = arn, mapeo = aes(y = expresión_log, x = muestra)) + + geom_point(aes(color = tiempo)) +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## diagrama de caja + +Podemos usar diagramas de caja para visualizar la distribución de expresiones genéticas +dentro de cada muestra: + +```{r boxplot, cache=FALSE, purl=TRUE} +ggplot(datos = rna, + mapeo = aes(y = expresión_log, x = muestra)) + + geom_boxplot() +``` + +Al agregar puntos al diagrama de caja, podemos tener una mejor idea del número de +mediciones y de su distribución: + +```{r boxplot-with-points, cache=FALSE, purl=TRUE} +ggplot(datos = rna, + mapeo = aes(y = expresión_log, x = muestra)) + + geom_jitter(alfa = 0.2, color = "tomate") + + geom_boxplot( alfa = 0) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío + +¿Observa cómo la capa del diagrama de caja está delante de la capa de fluctuación? ¿Qué +necesitas cambiar en el código para colocar el diagrama de caja debajo de los puntos? + +::::::::::::::: solución + +## Solución + +Deberíamos cambiar el orden de estas dos geoms: + +```{r boxplot-with-points2, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapeo = aes(y = expresión_log, x = muestra)) + + geom_boxplot(alpha = 0) + + geom_jitter(alpha = 0.2, color = "tomate") +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +Puede notar que los valores en el eje x todavía no se pueden leer correctamente +. Cambiemos la orientación de las etiquetas y ajustémoslas +vertical y horizontalmente para que no se superpongan. Puedes usar un ángulo de +90 grados, o experimentar para encontrar el ángulo apropiado para +etiquetas orientadas en diagonal: + +```{r boxplot-xaxis-rotated, cache=FALSE, purl=TRUE} +ggplot(datos = rna, + mapeo = aes(y = expresión_log, x = muestra)) + + geom_jitter(alfa = 0.2, color = "tomate") + + geom_boxplot( alfa = 0) + + tema(axis.text.x = element_text(ángulo = 90, hjust = 0.5, vjust = 0.5)) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío + +Agregue color a los puntos de datos en su diagrama de caja de acuerdo con la duración +de la infección (`tiempo`). + +_Pista:_ Verifique el "tiempo" de la clase. Considere cambiar la clase de +`time` de entero a factor directamente en el mapeo de ggplot. ¿Por qué +esto cambia la forma en que R hace el gráfico? + +::::::::::::::: solución + +## Solución + +```{r boxplot-color-time, cache=FALSE, purl=TRUE} +# time as integer +ggplot(data = rna, + mapping = aes(y = expression_log, + x = sample)) + + geom_jitter(alpha = 0.2, aes(color = time)) + + geom_boxplot(alpha = 0) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) + +# time as factor +ggplot(data = rna, + mapping = aes(y = expression_log, + x = sample)) + + geom_jitter(alpha = 0.2, aes(color = as.factor(time))) + + geom_boxplot(alpha = 0) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío + +Los diagramas de caja son resúmenes útiles, pero ocultan la _forma_ de la distribución +. Por ejemplo, si la distribución es bimodal, +no la veríamos en un diagrama de caja. Una alternativa al diagrama de caja es el diagrama del violín +, donde se dibuja la forma (de la densidad de puntos). + +- Reemplace el diagrama de caja con un diagrama de violín; ver `geom_violin()`. Rellena + los violines según el tiempo con el argumento `fill`. + +::::::::::::::: solución + +## Solución + +```{r, eval=TRUE, echo=TRUE, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapeo = aes(y = expresión_log, x = muestra)) + + geom_violin(aes(fill = as.factor(time))) + + tema(axis.text.x = element_text(ángulo = 90, hjust = 0.5, vjust = 0.5)) +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío + +- Modifique la trama del violín para completar los violines por "sexo". + +::::::::::::::: solución + +## Solución + +```{r, eval=TRUE, echo=TRUE, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_violin(aes(fill = sex)) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## Gráficos de líneas + +Calculemos la expresión media por duración de la infección para +los 10 genes que tienen los cambios logarítmicos más altos comparando el tiempo 8 versus +tiempo 0. Primero, necesitamos seleccionar los genes y crear un subconjunto de `rna` +llamado `sub_rna` que contiene los 10 genes seleccionados, luego necesitamos agrupar +los datos y calcular la expresión génica media dentro cada grupo: + +```{r, purl=TRUE} +rna_fc <- rna_fc %>% arrange(desc(time_8_vs_0)) + +genes_selected <- rna_fc$gene[1:10] + +sub_rna <- rna %>% + filter(gene %in% genes_selected) + +mean_exp_by_time <- sub_rna %>% + group_by(gene,time) %>% + summarize(mean_exp = mean(expression_log)) + +mean_exp_by_time +``` + +Podemos construir el gráfico lineal con la duración de la infección en el eje x +y la expresión media en el eje y: + +```{r first-time-series, purl=TRUE} +ggplot(datos = media_exp_por_tiempo, mapeo = aes(x = tiempo, y = media_exp)) + + geom_line() +``` + +Desafortunadamente, esto no funciona porque representamos los datos de todos los genes +juntos. Necesitamos decirle a ggplot que dibuje una línea para cada gen +modificando la función estética para incluir `grupo = gen`: + +```{r time-series-by-gene, purl=TRUE} +ggplot(datos = media_exp_por_tiempo, + mapeo = aes(x = tiempo, y = media_exp, grupo = gen)) + + geom_line() +``` + +Podremos distinguir genes en el gráfico si agregamos colores (usando +`color` también agrupa automáticamente los datos): + +```{r time-series-with-colors, purl=TRUE} +ggplot(datos = media_exp_por_tiempo, + mapeo = aes(x = tiempo, y = media_exp, color = gen)) + + geom_line() +``` + +## facetado + +`ggplot2` tiene una técnica especial llamada _facetado_ que permite al usuario +dividir un gráfico en múltiples (sub)gráficos en función de un factor incluido +en el conjunto de datos. Estas diferentes subtramas heredan las mismas propiedades +(límites de ejes, ticks, ...) para facilitar su comparación directa. +lo usaremos para hacer un gráfico lineal a lo largo del tiempo para cada gen: + +```{r first-facet, purl=TRUE} +ggplot(datos = media_exp_por_tiempo, + mapeo = aes(x = tiempo, y = media_exp)) + geom_line() + + facet_wrap(~ gen) +``` + +Aquí, tanto el eje x como el y tienen la misma escala para todas las subtramas. Usted +puede cambiar este comportamiento predeterminado modificando `escalas` para permitir +una escala libre para el eje y: + +```{r first-facet-scales, purl=TRUE} +ggplot(data = media_exp_por_tiempo, + mapeo = aes(x = tiempo, y = media_exp)) + + geom_line() + + facet_wrap(~ gen, escalas = "free_y") +``` + +Ahora nos gustaría dividir la línea en cada gráfico por el sexo de los ratones. +Para hacer eso necesitamos calcular la expresión media en el marco de datos +agrupado por "gen", "tiempo" y "sexo": + +```{r data-facet-by-gene-and-sex, purl=TRUE} +mean_exp_by_time_sex <- sub_rna %>% + group_by(gen, tiempo, sexo) %>% + resumen(mean_exp = mean(expression_log)) + +mean_exp_by_time_sex +``` + +Ahora podemos hacer el gráfico facetado dividiéndolo aún más por sexo usando +`color` (dentro de un solo gráfico): + +```{r facet-by-gene-and-sex, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapeo = aes(x = tiempo, y = mean_exp, color = sexo)) + + geom_line() + + facet_wrap(~ gen, escalas = "libre_y") +``` + +Por lo general, los gráficos con fondo blanco parecen más legibles cuando se imprimen. Nosotros +podemos configurar el fondo en blanco usando la función `theme_bw()`. +Además, podemos eliminar la cuadrícula: + +```{r facet-by-gene-and-sex-white-bg, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapeo = aes(x = tiempo, y = mean_exp, color = sexo)) + + geom_line() + + facet_wrap(~ gen, escalas = "free_y") + + theme_bw() + + tema(panel.grid = element_blank()) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío + +Utilice lo que acaba de aprender para crear un gráfico que represente cómo cambia la expresión promedio +de cada cromosoma durante la duración de la infección +. + +::::::::::::::: solución + +## Solución + +```{r mean-exp-chromosome-time-series, purl=TRUE} +mean_exp_by_chromosome <- arn %>% + group_by(chromosome_name, time) %>% + resumen(mean_exp = mean(expression_log)) + +ggplot(data = mean_exp_by_chromosome, mapeo = aes( x = tiempo, + y = media_exp)) + + geom_line() + + facet_wrap(~ nombre_cromosoma, escalas = "free_y") +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +La geometría `facet_wrap` extrae gráficos en un número arbitrario de +dimensiones para permitir que quepan limpiamente en una página. On the other hand, +the `facet_grid` geometry allows you to explicitly specify how you want +your plots to be arranged via formula notation (`rows ~ columns`; a `.` +can be used as a placeholder that indicates only one row or column). + +Modifiquemos el gráfico anterior para comparar cómo la expresión genética media +de hombres y mujeres ha cambiado a lo largo del tiempo: + +```{r mean-exp-time-facet-sex-rows, purl=TRUE} +# Una columna, faceta por filas +ggplot(data = media_exp_by_time_sex, + mapeo = aes(x = tiempo, y = media_exp, color = gen)) + + geom_line() + + facet_grid(sexo ~ .) +``` + +```{r mean-exp-time-facet-sex-columns, purl=TRUE} +# Una fila, faceta por columna +ggplot(data = media_exp_by_time_sex, + mapeo = aes(x = tiempo, y = media_exp, color = gen)) + + geom_line() + + facet_grid(. ~ sexo) +``` + +## temas `ggplot2` + +Además de `theme_bw()`, que cambia el fondo de la trama a blanco, +`ggplot2` viene con varios otros temas que pueden ser útiles para +cambiar rápidamente el aspecto de tu visualización. La lista completa de temas está +disponible en [https://ggplot2.tidyverse.org/reference/ggtheme.html](https://ggplot2.tidyverse.org/reference/ggtheme.html). +`theme_minimal()` y `theme_light()` son populares, y `theme_void()` +puede ser útil como punto de partida para crear un nuevo tema hecho a mano. + +El paquete [ggthemes](https://jrnold.github.io/ggthemes/reference/index.html) +proporciona una amplia variedad de opciones (incluido un tema de Excel 2003 +). The ggplot2 provides a list of +packages that extend the capabilities of `ggplot2`, including additional +themes. + +## Personalización + +Volvamos a la trama facetada de expresión media por tiempo y gen, +coloreada por sexo. + +Eche un vistazo a la hoja de trucos , +y piense en formas Podrías mejorar la trama. + +Ahora, podemos cambiar los nombres de los ejes a algo más informativo que +'tiempo' y 'media\_exp', y agregar un título a la figura: + +```{r mean_exp-time-with-right-labels, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapeo = aes(x = tiempo, y = mean_exp, color = sexo)) + + geom_line() + + facet_wrap(~ gen, escalas = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + labs(title = "Expresión genética media por duración de la infección", + x = "Duración de la infección (en días)", + y = "Expresión genética media") +``` + +Los ejes tienen nombres más informativos, pero su legibilidad se puede mejorar +aumentando el tamaño de fuente: + +```{r mean_exp-time-with-right-labels-xfont-size, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapeo = aes(x = tiempo, y = mean_exp, color = sexo)) + + geom_line() + + facet_wrap(~ gen, escalas = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + labs(title = "Expresión genética media por duración de la infección", + x = "Duración de la infección (en días)", + y = "Expresión genética media") + + tema(texto = elemento_texto(tamaño = 16)) +``` + +Tenga en cuenta que también es posible cambiar las fuentes de sus gráficos. Si +estás en Windows, es posible que tengas que instalar el [**`extrafont`** +paquete](https://cran.r-project.org/web/packages/extrafont /index.html). + +Podemos personalizar aún más el color del texto de los ejes x e y, el color de +la cuadrícula, etc. También podemos, por ejemplo, mover la leyenda a la parte superior +configurando `legend.position` en `"top"`. + +```{r mean_exp-time-with-theme, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + labs(title = "Mean gene expression by duration of the infection", + x = "Duration of the infection (in days)", + y = "Mean gene expression") + + theme(text = element_text(size = 16), + axis.text.x = element_text(colour = "royalblue4", size = 12), + axis.text.y = element_text(colour = "royalblue4", size = 12), + panel.grid = element_line(colour="lightsteelblue1"), + legend.position = "top") +``` + +Si le gustan más los cambios que creó que el tema predeterminado, +puede guardarlos como un objeto para poder aplicarlos fácilmente a otros +gráficos que pueda crear. Aquí hay un ejemplo con el histograma que hemos +creado previamente. + +```{r mean_exp-time-with-right-labels-xfont, cache=FALSE, purl=TRUE} +blue_theme <- theme(axis.text.x = element_text(colour = "royalblue4", + size = 12), + axis.text.y = element_text(colour = "royalblue4", + size = 12), + text = element_text(size = 16), + panel.grid = element_line(colour="lightsteelblue1")) + +ggplot(rna, aes(x = expression_log)) + + geom_histogram(bins = 20) + + blue_theme +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío + +Con toda esta información en la mano, tómate otros cinco minutos +para mejorar uno de los gráficos generados en este ejercicio o +para crear un hermoso gráfico propio. Utilice la hoja de trucos +de RStudio ggplot2 +para inspirarse. Aquí hay algunas ideas: + +- Vea si puede cambiar el grosor de las líneas. +- ¿Puedes encontrar una manera de cambiar el nombre de la leyenda? ¿Qué pasa con + sus etiquetas? (pista: busque una función ggplot que comience con + `scale_`) +- Intente usar una paleta de colores diferente o especifique manualmente los + colores para las líneas (consulte + [http://www.cookbook-r.com/Graphs/Colors\_(ggplot2)/](https://www.cookbook-r.com/Graphs/Colors_\\(ggplot2\\)/)). + +::::::::::::::: solución + +## Solución + +Por ejemplo, basado en esta trama: + +```{r, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapeo = aes(x = tiempo, y = mean_exp, color = sexo)) + + geom_line() + + facet_wrap(~ gen, escalas = "free_y") + + theme_bw() + + tema(panel.grid = element_blank()) +``` + +Podemos personalizarlo de las siguientes maneras: + +```{r, purl=TRUE} +# change the thickness of the lines +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line(size=1.5) + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + +# change the name of the legend and the labels +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + scale_color_discrete(name = "Gender", labels = c("F", "M")) + +# using a different color palette +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + scale_color_brewer(name = "Gender", labels = c("F", "M"), palette = "Dark2") + +# manually specifying the colors +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + scale_color_manual(name = "Gender", labels = c("F", "M"), + values = c("royalblue", "deeppink")) + +``` + +:::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## Componer tramas + +Faceting is a great tool for splitting one plot into multiple subplots, +but sometimes you may want to produce a single figure that contains +multiple independent plots, i.e. plots that are based on different +variables or even different data frames. + +Comencemos creando los dos gráficos que queremos organizar uno al lado del otro: +: + +El primer gráfico cuenta el número de genes únicos por cromosoma. +primero necesitamos reordenar los niveles de `chromosome_name` y filtrar los +genes únicos por cromosoma. También cambiamos la escala del eje y a una escala +log10 para una mejor legibilidad. + +```{r sub1, purl=TRUE} +arn$chromosome_name <- factor(arn$chromosome_name, + niveles = c(1:19,"X","Y")) + +count_gene_chromosome <- arn %> % select(nombre_cromosoma, gen) %>% + distintivo() %>% ggplot() + + geom_bar(aes(x = nombre_cromosoma), fill = "verdemar", + posición = "esquivar", estadística = "contar") + + labs(y = "log10(n genes)", x = "cromosoma") + + scale_y_log10() + +recuento_gene_cromosoma +``` + +A continuación, también eliminamos la leyenda por completo estableciendo +`legend.position` en `"none"`. + +```{r sub2, purl=TRUE} +exp_boxplot_sex <- ggplot(rna, aes(y=expression_log, x = as.factor(time), + color=sex)) + + geom_boxplot(alpha = 0) + + labs(y = "Experiencia genética media", + x = "tiempo") + theme(legend.position = "none") + +exp_boxplot_sex +``` + +El paquete [**patchwork**](https://github.com/thomasp85/patchwork) +proporciona un enfoque elegante para combinar figuras usando `+` para +organizar figuras (normalmente de lado). al lado). Más específicamente, `|` +los organiza explícitamente uno al lado del otro y `/` los apila uno encima del otro +. + +```{r install-patchwork, message=FALSE, eval=FALSE, purl=TRUE} +instalar.paquetes("patchwork") +``` + +```{r patchworkplot1, purl=TRUE} +biblioteca("patchwork") +count_gene_chromosome + exp_boxplot_sex +## o count_gene_chromosome | exp_boxplot_sexo +``` + +```{r patchwork2, purl=TRUE} +count_gene_chromosome / exp_boxplot_sex +``` + +Podemos combinar un mayor control del diseño de la composición final con +`plot_layout` para crear diseños más complejos: + +```{r patchwork3, purl=TRUE} +count_gene_chromosome + exp_boxplot_sex + plot_layout(ncol = 1) +``` + +```{r patchwork4, purl=TRUE} +count_gene_chromosome + + (count_gene_chromosome + exp_boxplot_sex) + + exp_boxplot_sex + + plot_layout(ncol = 1) +``` + +El último gráfico también se puede crear usando los compositores `|` y `/`: + +```{r patchwork5, purl=TRUE} +count_gene_chromosome / + (count_gene_chromosome | exp_boxplot_sex) / + exp_boxplot_sex +``` + +Obtenga más información sobre `patchwork` en su +[página web](https://patchwork.data-imaginist.com/) o en este +[video](https://www.youtube. es/watch?v=0m4yywqNPVY). + +Otra opción es el paquete **`gridExtra`** que permite combinar +ggplots separados en una sola figura usando `grid.arrange()`: + +```{r install-gridextra, message=FALSE, eval=FALSE, purl=TRUE} +instalar.paquetes("gridExtra") +``` + +```{r gridarrange-example, message=FALSE, fig.width=10, purl=TRUE} +biblioteca("gridExtra") +grid.arrange(count_gene_chromosome, exp_boxplot_sex, ncol = 2) +``` + +Además de los argumentos `ncol` y `nrow`, utilizados para hacer arreglos +simples, existen herramientas para [construir diseños +más complejos](https://cran.r-project. org/web/packages/gridExtra/vignettes/arrangeGrob.html). + +## Exportar parcelas + +Después de crear su trama, puede guardarla en un archivo en su formato +favorito. La pestaña Exportar en el panel **Trazado** en RStudio guardará sus +trazados en baja resolución, lo que no será aceptado por muchas revistas y +no se escalará bien para los carteles. + +En su lugar, use la función `ggsave()`, que le permite cambiar fácilmente la dimensión +y la resolución de su gráfico ajustando los argumentos +apropiados (`ancho`, `alto` y `dpi` ). + +Asegúrese de tener la carpeta `fig_output/` en su directorio de trabajo. + +```{r ggsave-example, eval=FALSE, purl=TRUE} +my_plot <- ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + labs(title = "Mean gene expression by duration of the infection", + x = "Duration of the infection (in days)", + y = "Mean gene expression") + + guides(color=guide_legend(title="Gender")) + + theme_bw() + + theme(axis.text.x = element_text(colour = "royalblue4", size = 12), + axis.text.y = element_text(colour = "royalblue4", size = 12), + text = element_text(size = 16), + panel.grid = element_line(colour="lightsteelblue1"), + legend.position = "top") +ggsave("fig_output/mean_exp_by_time_sex.png", my_plot, width = 15, + height = 10) + +# This also works for grid.arrange() plots +combo_plot <- grid.arrange(count_gene_chromosome, exp_boxplot_sex, + ncol = 2, widths = c(4, 6)) +ggsave("fig_output/combo_plot_chromosome_sex.png", combo_plot, + width = 10, dpi = 300) +``` + +Nota: Los parámetros `ancho` y `alto` también determinan el tamaño de fuente +en el gráfico guardado. + +```{r final-challenge, eval=FALSE, purl=TRUE, echo=FALSE} +### Desafío de trama final: +## Con toda esta información en la mano, tómate otros cinco +## minutos para mejorar una de las tramas generadas en este +# # Haz ejercicio o crea un hermoso gráfico propio. Utilice la hoja de referencia de RStudio +## ggplot2 para inspirarse: +## https://raw.githubusercontent.com/rstudio/cheatsheets/main/data-visualization.pdf +``` + +## Otros paquetes para visualización. + +`ggplot2` es un paquete muy poderoso que encaja muy bien en nuestra canalización de datos \*tidy* y _herramientas tidy_. Hay otros paquetes de visualización + en R que no deben ignorarse. + +### Gráficos básicos + +El sistema de gráficos predeterminado que viene con R, a menudo llamado _base R +gráficos_ es simple y rápido. Se basa en el \*modelo de pintor o lienzo +\*, donde diferentes resultados se superponen directamente uno encima del otro +(consulte la figura @ref(fig:paintermodel)). This is a fundamental +difference with `ggplot2` (and with `lattice`, described below), that +returns dedicated objects, that are rendered on screen or in a file, and +that can even be updated. + +```{r paintermodel, fig.width=12, fig.height=4, fig.cap="Successive layers added on top of each other."} +par(mfrow = c(1, 3)) +plot(1:20, main = "Primera capa, producida con plot(1:20)") + +plot(1:20, main = "Una línea roja horizontal, agregada con abline(h = 10)") +abline(h = 10, col = "red") + +plot(1:20, main = "Un rectángulo , agregado con rect(5, 5, 15, 15)") +abline(h = 10, col = "red") +rect(5, 5, 15, 15, lwd = 3 ) +``` + +Otra diferencia principal es que la función de trazado de los gráficos base intenta +hacer _lo correcto_ según su tipo de entrada, es decir, adaptarán +su comportamiento según la clase de su entrada. De nuevo, esto es muy +diferente de lo que tenemos en `ggplot2`, que solo acepta marcos de datos +como entrada y que requiere que los gráficos se construyan poco a poco. + +```{r plotmethod, fig.width=8, fig.height=8, fig.cap="Plotting boxplots (top) and histograms (bottom) vectors (left) or a matrices (right)."} +par(mfrow = c(2, 2)) +boxplot(rnorm(100), + main = "Gráfico de caja de rnorm(100)") +boxplot(matrix(rnorm( 100), ncol = 10), + main = "Gráfico de caja de la matriz(rnorm(100), ncol = 10)") +hist(rnorm(100)) +hist( matriz(norma(100), ncol = 10)) +``` + +El enfoque listo para usar en gráficos base puede ser muy eficiente para +figuras simples y estándar, que se pueden producir muy rápidamente con una sola línea de código +y una sola función, como `trama`, o `hist`, o +`boxplot`, ... Sin embargo, los valores predeterminados no siempre son los más atractivos +y el ajuste de las figuras, especialmente cuando se vuelven más complejos (por ejemplo, +para producir facetas), puede volverse largo y engorroso. + +### El paquete de celosía + +El paquete **`lattice`** es similar a `ggplot2` en el sentido de que utiliza +marcos de datos como entrada, devuelve objetos gráficos y admite facetado. +Sin embargo, `lattice` no se basa en la gramática de los gráficos y tiene una interfaz más +complicada. + +Una buena referencia para el paquete `lattice` es @latticebook. + +:::::::::::::::::::::::::::::::::::::::: puntos clave + +- Visualización en R + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/es/episodes/60-next-steps.Rmd b/locale/es/episodes/60-next-steps.Rmd new file mode 100644 index 000000000..56fc00cde --- /dev/null +++ b/locale/es/episodes/60-next-steps.Rmd @@ -0,0 +1,462 @@ +--- +source: Rmd +title: Próximos pasos +teaching: 45 +exercises: 45 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Presentar el proyecto Bioconductor. +- Introducir la noción de contenedores de datos. +- Brinde una descripción general del "Experimento resumido", ampliamente utilizado en + análisis ómicos. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- ¿Qué es un "experimento resumido"? +- ¿Qué es un bioconductor? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Próximos pasos + +```{r, echo=FALSE, message=FALSE} +library("tidyverse") +``` + +Los datos en bioinformática suelen ser complejos. Para solucionar esto, los desarrolladores de +definen contenedores de datos especializados (denominados clases) que +coinciden con las propiedades de los datos que necesitan manejar. + +Este aspecto es fundamental para el proyecto **Bioconductor**[^Bioconductor] +, que utiliza la misma **infraestructura de datos central** en todos los paquetes. Esto +ciertamente contribuyó al éxito de Bioconductor. Se recomienda a los desarrolladores del paquete de bioconductores +que utilicen la infraestructura existente para +proporcionar coherencia, interoperabilidad y estabilidad al proyecto en su conjunto +. + +[^Bioconductor]: El [Bioconductor](https://www.bioconductor.org) fue + iniciado por Robert Gentleman, uno de los dos creadores del lenguaje R + . Bioconductor proporciona herramientas dedicadas al análisis de datos ómicos + . Bioconductor utiliza el lenguaje de programación estadística R + y es de código abierto y desarrollo abierto. + +Para ilustrar dicho contenedor de datos ómicos, presentaremos la clase +`SummarizedExperiment`. + +## Experimento resumido + +La siguiente figura representa la anatomía de la clase SummarizedExperiment. + +```{r SE, echo=FALSE, out.width="80%"} +knitr::include_graphics("https://uclouvain-cbio.github.io/WSBIM1322/figs/SE.svg") +``` + +Los objetos de la clase SummarizedExperiment contienen: + +- **Uno (o más) ensayos** que contienen los datos ómicos cuantitativos + (datos de expresión), almacenados como un objeto similar a una matriz. Características (genes, + transcripciones, proteínas, ...) se definen a lo largo de las filas y las muestras + a lo largo de las columnas. + +- Una ranura de **metadatos de muestra** que contiene covariables de muestra, almacenada como un marco de datos + . Las filas de esta tabla representan muestras (las filas coinciden exactamente con las + columnas de los datos de la expresión). + +- Una ranura de **metadatos de características** que contiene covariables de características, almacenada como + un marco de datos. Las filas de este marco de datos coinciden exactamente con las filas de los datos de expresión + . + +La naturaleza coordinada del `Experimento resumido` garantiza que +durante la manipulación de datos, las dimensiones de las diferentes ranuras +siempre coincidirán (es decir, las columnas en los datos de expresión y luego las filas en +los metadatos de muestra, así como las filas en los datos de expresión y +metadatos de características) durante la manipulación de datos. Por ejemplo, si tuviéramos que +excluir una muestra del ensayo, se eliminaría automáticamente +de los metadatos de la muestra en la misma operación. + +Las ranuras de metadatos pueden generar covariables adicionales +(columnas) sin afectar las otras estructuras. + +### Crear un experimento resumido + +Para crear un `Experimento resumido`, crearemos los +componentes individuales, es decir, la matriz de recuento, la muestra y el gen +metadatos a partir de archivos csv. Por lo general, así es como se proporcionan +los datos de RNA-Seq (después de que se hayan procesado los datos sin procesar). + +```{r, echo=FALSE, message=FALSE} +rna <- read_csv("data/rnaseq.csv") + +## count matrix +counts <- rna %>% + select(gene, sample, expression) %>% + pivot_wider(names_from = sample, + values_from = expression) + +## convert to matrix and set row names +count_matrix <- counts %>% select(-gene) %>% as.matrix() +rownames(count_matrix) <- counts$gene + +## sample annotation +sample_metadata <- rna %>% + select(sample, organism, age, sex, infection, strain, time, tissue, mouse) + +## remove redundancy +sample_metadata <- unique(sample_metadata) + +## gene annotation +gene_metadata <- rna %>% + select(gene, ENTREZID, product, ensembl_gene_id, external_synonym, + chromosome_name, gene_biotype, phenotype_description, + hsapiens_homolog_associated_gene_name) + +# remove redundancy +gene_metadata <- unique(gene_metadata) + +## write to csv +write.csv(count_matrix, file = "data/count_matrix.csv") +write.csv(gene_metadata, file = "data/gene_metadata.csv", row.names = FALSE) +write.csv(sample_metadata, file = "data/sample_metadata.csv", row.names = FALSE) +``` + +- **Una matriz de expresión**: cargamos la matriz de recuento, especificando que + las primeras columnas contienen nombres de filas/genes, y convertimos el + `data.frame` en una `matriz`. Puede descargarlo + [aquí](https://carpentries-incubator.github.io/bioc-intro/data/count_matrix.csv). + +```{r} +count_matrix <- read.csv("data/count_matrix.csv", + row.names = 1) %>% + as.matrix() + +count_matrix[1:5, ] +dim(count_matrix) +``` + +- **Una tabla que describe las muestras**, disponible + [aquí](https://carpentries-incubator.github.io/bioc-intro/data/sample_metadata.csv). + +```{r} +sample_metadata <- read.csv("data/sample_metadata.csv") +sample_metadata +dim(sample_metadata) +``` + +- **Una tabla que describe los genes**, disponible + [aquí](https://carpentries-incubator.github.io/bioc-intro/data/gene_metadata.csv). + +```{r} +gene_metadata <- read.csv("data/gene_metadata.csv") +gene_metadata[1:10, 1:4] +dim(gene_metadata) +``` + +Crearemos un `Experimento resumido` a partir de estas tablas: + +- La matriz de recuento que se utilizará como **`ensayo`** + +- La tabla que describe las muestras se utilizará como espacio de metadatos \*\*muestra + \*\* + +- La tabla que describe los genes se utilizará como espacio de **características + metadatos** + +Para hacer esto podemos juntar las diferentes partes usando el constructor +`SummarizedExperiment`: + +```{r, message=FALSE, warning=FALSE} +## BiocManager::install("SummarizedExperiment") +library("SummarizedExperiment") +``` + +Primero, nos aseguramos de que las muestras estén en el mismo orden en la matriz de conteo +y la anotación de muestra, y lo mismo para los genes en +la matriz de conteo y la anotación de genes. + +```{r} +stopifnot(rownames(count_matrix) == gene_metadata$gene) +stopifnot(colnames(count_matrix) == sample_metadata$sample) +``` + +```{r} +se <- SummarizedExperiment(assays = list(counts = count_matrix), + colData = sample_metadata, + rowData = gene_metadata) +se +``` + +### Guardar datos + +Exportar datos a una hoja de cálculo, como hicimos en un episodio anterior, tiene +varias limitaciones, como las descritas en el primer capítulo +(posibles inconsistencias con `,` y `.` para los separadores decimales y +falta de definiciones de tipos de variables). Además, exportar datos a una hoja de cálculo +solo es relevante para datos rectangulares como marcos de datos +y matrices. + +Una forma más general de guardar datos, que es específica de R y +garantiza que funciona en cualquier sistema operativo, es utilizar la función `saveRDS` +. Guardar objetos como este generará una representación binaria +en el disco (usando la extensión de archivo `rds` aquí), que +se puede volver a cargar en R usando la función `readRDS`. + +```{r, eval=FALSE} +saveRDS(se, file = "data_output/se.rds") +rm(se) +se <- readRDS("data_output/se.rds") +head(se) +``` + +Para concluir, cuando se trata de guardar datos de R que se cargarán +nuevamente en R, guardar y cargar con `saveRDS` y `readRDS` es el enfoque preferido +. Si es necesario compartir datos tabulares con alguien +que no esté usando R, entonces exportarlos a una hoja de cálculo basada en texto es una +buena alternativa. + +Usando esta estructura de datos, podemos acceder a la matriz de expresión con +la función `ensayo`: + +```{r} +head(assay(se)) +dim(assay(se)) +``` + +Podemos acceder a los metadatos de muestra usando la función `colData`: + +```{r} +colData(se) +dim(colData(se)) +``` + +También podemos acceder a los metadatos de la característica usando la función `rowData`: + +```{r} +head(rowData(se)) +dim(rowData(se)) +``` + +### Subconjunto de un experimento resumido + +SummarizedExperiment se puede subconjunto como con marcos de datos, con +numéricos o con caracteres lógicos. + +A continuación, creamos una nueva instancia de la clase SummarizedExperiment que +contiene solo las 5 primeras características para las 3 primeras muestras. + +```{r} +se1 <- se[1:5, 1:3] +se1 +``` + +```{r} +colData(se1) +rowData(se1) +``` + +También podemos usar la función `colData()` para crear un subconjunto de algo de +los metadatos de muestra o `rowData()` para crear un subconjunto de algo de los metadatos de característica +. Por ejemplo, aquí conservamos solo los miARN y las muestras no +infectadas: + +```{r} +se1 <- se[rowData(se)$gene_biotype == "miRNA", + colData(se)$infection == "NonInfected"] +se1 +assay(se1) +colData(se1) +rowData(se1) +``` + + + + + + + + + + + + + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío + +Extraiga los niveles de expresión génica de los 3 primeros genes en muestras +en el tiempo 0 y en el tiempo 8. + +::::::::::::::: solution + +## Solución + +```{r, purl=FALSE} +assay(se)[1:3, colData(se)$time != 4] + +# Equivalent to +assay(se)[1:3, colData(se)$time == 0 | colData(se)$time == 8] +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafío + +Verifique que obtenga los mismos valores usando la tabla larga `rna`. + +::::::::::::::: solution + +## Solución + +```{r, purl=FALSE} +rna |> + filter(gene %in% c("Asl", "Apod", "Cyd2d22")) |> + filter(time != 4) |> select(expression) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +La tabla larga y el `Experimento resumido` contienen la misma información +, pero simplemente están estructurados de manera diferente. Cada enfoque tiene sus +propias ventajas: el primero es una buena opción para los paquetes `tidyverse`, +mientras que el segundo es la estructura preferida para muchos pasos de procesamiento bioinformático y +estadístico. Por ejemplo, un RNA-Seq típico analiza usando +el paquete `DESeq2`. + +#### Agregar variables a los metadatos + +También podemos agregar información a los metadatos. +Supongamos que desea agregar el centro donde se recolectaron las muestras... + +```{r} +colData(se)$center <- rep("University of Illinois", nrow(colData(se))) +colData(se) +``` + +¡Esto ilustra que los espacios de metadatos pueden crecer indefinidamente sin que +afecte a las otras estructuras! + +### ordenadoResumidoExperimento + +Quizás se pregunte: ¿podemos usar los comandos de tidyverse para interactuar con +objetos `SummarizedExperiment`? La respuesta es sí, podemos hacerlo con el paquete +`tidySummarizedExperiment`. + +Recuerde cómo se ve nuestro objeto SummarizedExperiment: + +```{r, message=FALSE} +se +``` + +Cargue `tidySummarizedExperiment` y luego eche un vistazo al objeto se +nuevamente. + +```{r, message=FALSE} +#BiocManager::install("tidySummarizedExperiment") +library("tidySummarizedExperiment") + +se +``` + +Sigue siendo un objeto `SummarizedExperiment`, por lo que mantiene la estructura eficiente +, pero ahora podemos verlo como un tibble. Tenga en cuenta que la primera línea de +el resultado dice esto, es una abstracción `SummarizedExperiment`\-`tibble` +. También podemos ver en la segunda línea del resultado el +número de transcripciones y muestras. + +Si queremos volver a la vista estándar `Experimento resumido`, +podemos hacerlo. + +```{r} +options("restore_SummarizedExperiment_show" = TRUE) +se +``` + +Pero aquí usamos la vista tibble. + +```{r} +options("restore_SummarizedExperiment_show" = FALSE) +se +``` + +Ahora podemos usar los comandos de tidyverse para interactuar con el objeto +`SummarizedExperiment`. + +Podemos usar `filter` para filtrar filas usando una condición, por ejemplo, para ver +todas las filas de una muestra. + +```{r} +se %>% filter(.sample == "GSM2545336") +``` + +Podemos usar `select` para especificar las columnas que queremos ver. + +```{r} +se %>% select(.sample) +``` + +Podemos usar `mutate` para agregar información de metadatos. + +```{r} +se %>% mutate(center = "Heidelberg University") +``` + +También podemos combinar comandos con la canalización tidyverse `%>%`. Por ejemplo, +, podríamos combinar `group_by` y `summarise` para obtener los recuentos totales de +para cada muestra. + +```{r} +se %>% + group_by(.sample) %>% + summarise(total_counts=sum(counts)) +``` + +Podemos tratar el objeto ordenado SummarizedExperiment como un tibble normal +para trazar. + +Aquí trazamos la distribución de recuentos por muestra. + +```{r tidySE-plot} +se %>% + ggplot(aes(counts + 1, group=.sample, color=infection)) + + geom_density() + + scale_x_log10() + + theme_bw() +``` + +Para obtener más información sobre tidySummarizedExperiment, consulte el sitio web del paquete[aquí](https://stemangiola.github.io/tidySummarizedExperiment/). + +**Llevar el mensaje a casa** + +- `SummarizedExperiment` representa una forma eficiente de almacenar y + manejar datos ómicos. + +- Se utilizan en muchos paquetes de Bioconductores. + +Si sigues la próxima formación centrada en el análisis de secuenciación de ARN, +aprenderás a utilizar el paquete Bioconductor `DESeq2` para realizar algunos +análisis de expresión diferencial. Todo el análisis del paquete `DESeq2` +se maneja en un `SummarizedExperiment`. + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Bioconductor es un proyecto que proporciona soporte y paquetes para la + comprensión de datos biológicos de alto rendimiento. +- Un `Experimento resumido` es un tipo de objeto útil para almacenar y + administrar datos ómicos de alto rendimiento. + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/es/index.md b/locale/es/index.md new file mode 100644 index 000000000..92eb9abe6 --- /dev/null +++ b/locale/es/index.md @@ -0,0 +1,18 @@ +--- +permalink: índice.html +site: papel de lija::sitio_papel de lija +--- + +## Acerca de este curso + +::::::::::::::::::::::::::::::::::::::::::::::: prerrequisito + +## Requisitos previos + +- Familiaridad con datos tabulares y hojas de cálculo. + +:::::::::::::::::::::::::::::::::::::::::::::::::::::::: + + + + diff --git a/locale/es/instructors/instructor-notes.md b/locale/es/instructors/instructor-notes.md new file mode 100644 index 000000000..1af091e31 --- /dev/null +++ b/locale/es/instructors/instructor-notes.md @@ -0,0 +1,9 @@ +--- +title: Notas del instructor +--- + +ARREGLARME + + + + diff --git a/locale/es/learners/discuss.md b/locale/es/learners/discuss.md new file mode 100644 index 000000000..5668a8eeb --- /dev/null +++ b/locale/es/learners/discuss.md @@ -0,0 +1,9 @@ +--- +title: Discusión +--- + +ARREGLARME + + + + diff --git a/locale/es/learners/reference.md b/locale/es/learners/reference.md new file mode 100644 index 000000000..d61977569 --- /dev/null +++ b/locale/es/learners/reference.md @@ -0,0 +1,11 @@ +--- +{} +--- + +## Glosario + +ARREGLARME + + + + diff --git a/locale/es/learners/setup.md b/locale/es/learners/setup.md new file mode 100644 index 000000000..59eb9acdb --- /dev/null +++ b/locale/es/learners/setup.md @@ -0,0 +1,158 @@ +--- +title: Configuración +--- + +- Asegúrese de tener a mano un editor de hojas de cálculo, como + LibreOffice, Microsoft Excel o Google Sheets. + +- Instale R, RStudio y paquetes (ver más abajo). + +### R y RStudio + +- R y RStudio son descargas e instalaciones independientes. R es el + entorno informático estadístico subyacente, pero usar R solo + no es divertido. RStudio es un entorno de desarrollo gráfico integrado + (IDE) que hace que el uso de R sea mucho más fácil e interactivo. Necesita + para instalar R antes de instalar RStudio. Después de instalar ambos programas + , necesitarás instalar algunos paquetes R específicos dentro de + RStudio. Siga las instrucciones a continuación para su sistema operativo, + y luego siga las instrucciones para instalar paquetes. + +### Estas ejecutando Windows + +
+ +::::::::::::::: solución + +## Si ya tienes R y RStudio instalados + +- Abra RStudio y haga clic en "Ayuda" > "Buscar actualizaciones". Si hay una nueva versión + disponible, salga de RStudio y descargue la última versión de RStudio. + +- Para verificar qué versión de R estás usando, inicia RStudio y lo primero + que aparece en la consola indica la versión de R que estás + ejecutando. Alternativamente, puede escribir `sessionInfo()`, que también mostrará + qué versión de R está ejecutando. Vaya + al [sitio web de CRAN](https://cran.r-project.org/bin/windows/base/) y verifique + si hay una versión más reciente disponible. Si es así, descárguelo e instálelo + . Puede [consulte aquí](https://cran.r-project.org/bin/windows/base/rw-FAQ.html#How-do-I-UNinstall-R_003f) para obtener + más información sobre cómo eliminar versiones antiguas de su sistema si así lo desea. + +- Siga los pasos de las instrucciones [para todos](#para-todos) en la + parte inferior de esta página. + +:::::::::::::::::::::::::::: + +::::::::::::::: solución + +## Si no tienes R y RStudio instalados + +- Descargue R desde + el [sitio web de CRAN](https://cran.r-project.org/bin/windows/base/release.htm). + +- Ejecute el archivo `.exe` que acaba de descargar + +- Vaya a la [página de descarga de RStudio](https://www.rstudio.com/products/rstudio/download/#download) + +- En _Todos los instaladores_ seleccione **RStudio xxxx.yy.zz-uuu.exe - Windows 10/11** (donde x, y, z y u representan números de versión) + +- Haga doble clic en el archivo para instalarlo. + +- Una vez que esté instalado, abra RStudio para asegurarse de que funcione y no reciba ningún mensaje de error + . + +- Siga los pasos de las instrucciones [para todos](#para-todos) en la + parte inferior de esta página. + +:::::::::::::::::::::::::::: + +### Estás ejecutando macOS + +
+ +::::::::::::::: solución + +## Si ya tienes R y RStudio instalados + +- Abra RStudio y haga clic en "Ayuda" > "Buscar actualizaciones". Si hay una nueva versión + disponible, salga de RStudio y descargue la última versión de RStudio. + +- Para comprobar la versión de R que estás utilizando, inicia RStudio y lo primero + que aparece en el terminal indica la versión de R que estás ejecutando. Alternativamente, puede escribir `sessionInfo()`, que + también mostrará qué versión de R está ejecutando. Vaya + al [sitio web de CRAN](https://cran.r-project.org/bin/macosx/) y verifique + si hay una versión más reciente disponible. Si es así, descárguelo e instálelo + . + +- Siga los pasos de las instrucciones [para todos](#para-todos) en la + parte inferior de esta página. + +:::::::::::::::::::::::::::: + +::::::::::::::: solución + +## Si no tienes R y RStudio instalados + +- Descargue R desde + el [sitio web de CRAN](https://cran.r-project.org/bin/macosx/). + +- Seleccione el archivo `.pkg` para la última versión de R + +- Haga doble clic en el archivo descargado para instalar R + +- También es una buena idea instalar [XQuartz](https://www.xquartz.org/) (necesario + en algunos paquetes) + +- Vaya a la [página de descarga de RStudio](https://www.rstudio.com/products/rstudio/download/#download) + +- En _Todos los instaladores_ seleccione **RStudio xxxx.yy.zz-uuu.dmg - macOS 10.15+** (donde x, y, z y u representan números de versión) + +- Haga doble clic en el archivo para instalar RStudio + +- Una vez que esté instalado, abra RStudio para asegurarse de que funcione y no reciba ningún mensaje de error + . + +- Siga los pasos de las instrucciones [para todos](#para-todos) en la + parte inferior de esta página. + +:::::::::::::::::::::::::::: + +### Estás ejecutando Linux + +
+ +::::::::::::::: solución + +## Instale R usando su administrador de paquetes y RStudio + +- Siga las instrucciones para su distribución + de [CRAN](https://cloud.r-project.org/bin/linux), ellas brindan información + para obtener la versión más reciente de R para distribuciones comunes. Para la mayoría de las distribuciones + , puede usar su administrador de paquetes (por ejemplo, para Debian/Ubuntu ejecute + `sudo apt-get install r-base`, y para Fedora `sudo yum install R`), pero + no recomendamos este enfoque ya que las versiones proporcionadas por este + generalmente están desactualizadas. En cualquier caso, asegúrese de tener al menos R 4.2.0. +- Vaya a la página de descarga de RStudio + +- En _Todos los instaladores_ seleccione la versión que coincida con su distribución e + instálela con su método preferido (por ejemplo, con Debian/Ubuntu `sudo dpkg -i rstudio-xxxx.yy.zz-uuu-amd64.deb ` en la terminal). +- Una vez que esté instalado, abra RStudio para asegurarse de que funcione y no reciba ningún mensaje de error + . +- Sigue los pasos de las [instrucciones para todos](#para-todos) + +:::::::::::::::::::::::::::: + +### Para todo el mundo + +Después de instalar R y RStudio, necesita instalar un par de paquetes +que se utilizarán durante el taller. También aprenderemos +sobre la instalación de paquetes durante el curso para explicar los siguientes comandos +. Por ahora, simplemente siga las instrucciones a continuación: + +- Inicie RStudio haciendo doble clic en el icono y luego escriba: + +```r +install.packages(c("BiocManager", "remotes")) +BiocManager::install(c("tidyverse", "SummarizedExperiment", "hexbin", + "patchwork", "gridExtra ", "lubricar")) +``` diff --git a/locale/es/profiles/learner-profiles.md b/locale/es/profiles/learner-profiles.md new file mode 100644 index 000000000..5ea1d5bc9 --- /dev/null +++ b/locale/es/profiles/learner-profiles.md @@ -0,0 +1,5 @@ +--- +title: ARREGLARME +--- + +Este es un archivo de marcador de posición. Por favor agregue contenido aquí. diff --git a/locale/fr/CODE_OF_CONDUCT.md b/locale/fr/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..a820b8df5 --- /dev/null +++ b/locale/fr/CODE_OF_CONDUCT.md @@ -0,0 +1,12 @@ +--- +title: Contributor Code of Conduct +--- + +As contributors and maintainers of this project, +we pledge to follow the [The Carpentries Code of Conduct][coc]. + +Instances of abusive, harassing, or otherwise unacceptable behavior +may be reported by following our [reporting guidelines][coc-reporting]. + +[coc-reporting]: https://docs.carpentries.org/topic_folders/policies/incident-reporting.html +[coc]: https://docs.carpentries.org/topic_folders/policies/code-of-conduct.html diff --git a/locale/fr/CONTRIBUTING.md b/locale/fr/CONTRIBUTING.md new file mode 100644 index 000000000..5dfea562d --- /dev/null +++ b/locale/fr/CONTRIBUTING.md @@ -0,0 +1,151 @@ +# Contributing + +[Software Carpentry][swc-site] and [Data Carpentry][dc-site] are open source projects, +and we welcome contributions of all kinds: +new lessons, +fixes to existing material, +bug reports, +and reviews of proposed changes are all welcome. + +## Contributor Agreement + +By contributing, +you agree that we may redistribute your work under [our license](LICENSE.md). +In exchange, +we will address your issues and/or assess your change proposal as promptly as we can, +and help you become a member of our community. +Everyone involved in [Software Carpentry][swc-site] and [Data Carpentry][dc-site] +agrees to abide by our [code of conduct](CONDUCT.md). + +## How to Contribute + +The easiest way to get started is to file an issue +to tell us about a spelling mistake, +some awkward wording, +or a factual error. +This is a good way to introduce yourself +and to meet some of our community members. + +1. If you do not have a [GitHub][github] account, + you can [send us comments by email][contact]. + However, + we will be able to respond more quickly if you use one of the other methods described below. + +2. If you have a [GitHub][github] account, + or are willing to [create one][github-join], + but do not know how to use Git, + you can report problems or suggest improvements by [creating an issue][issues]. + This allows us to assign the item to someone + and to respond to it in a threaded discussion. + +3. If you are comfortable with Git, + and would like to add or change material, + you can submit a pull request (PR). + Instructions for doing this are [included below](#using-github). + +## Where to Contribute + +1. If you wish to change this lesson, + please work in , + which can be viewed at . + +2. If you wish to change the example lesson, + please work in , + which documents the format of our lessons + and can be viewed at . + +3. If you wish to change the template used for workshop websites, + please work in . + The home page of that repository explains how to set up workshop websites, + while the extra pages in + provide more background on our design choices. + +4. If you wish to change CSS style files, tools, + or HTML boilerplate for lessons or workshops stored in `_includes` or `_layouts`, + please work in . + +## What to Contribute + +There are many ways to contribute, +from writing new exercises and improving existing ones +to updating or filling in the documentation +and submitting [bug reports][issues] +about things that don't work, aren't clear, or are missing. +If you are looking for ideas, +please see [the list of issues for this repository][issues], +or the issues for [Data Carpentry][dc-issues] +and [Software Carpentry][swc-issues] projects. + +Comments on issues and reviews of pull requests are just as welcome: +we are smarter together than we are on our own. +Reviews from novices and newcomers are particularly valuable: +it's easy for people who have been using these lessons for a while +to forget how impenetrable some of this material can be, +so fresh eyes are always welcome. + +## What _Not_ to Contribute + +Our lessons already contain more material than we can cover in a typical workshop, +so we are usually _not_ looking for more concepts or tools to add to them. +As a rule, +if you want to introduce a new idea, +you must (a) estimate how long it will take to teach +and (b) explain what you would take out to make room for it. +The first encourages contributors to be honest about requirements; +the second, to think hard about priorities. + +We are also not looking for exercises or other material that only run on one platform. +Our workshops typically contain a mixture of Windows, macOS, and Linux users; +in order to be usable, +our lessons must run equally well on all three. + +## Using GitHub + +If you choose to contribute via GitHub, +you may want to look at +[How to Contribute to an Open Source Project on GitHub][how-contribute]. +In brief: + +1. The published copy of the lesson is in the `gh-pages` branch of the repository + (so that GitHub will regenerate it automatically). + Please create all branches from that, + and merge the [master repository][repo]'s `gh-pages` branch into your `gh-pages` branch + before starting work. + Please do _not_ work directly in your `gh-pages` branch, + since that will make it difficult for you to work on other contributions. + +2. We use [GitHub flow][github-flow] to manage changes: + 1. Create a new branch in your desktop copy of this repository for each significant change. + 2. Commit the change in that branch. + 3. Push that branch to your fork of this repository on GitHub. + 4. Submit a pull request from that branch to the [master repository][repo]. + 5. If you receive feedback, + make changes on your desktop and push to your branch on GitHub: + the pull request will update automatically. + +Each lesson has two maintainers who review issues and pull requests +or encourage others to do so. +The maintainers are community volunteers, +and have final say over what gets merged into the lesson. + +## Other Resources + +General discussion of [Software Carpentry][swc-site] and [Data Carpentry][dc-site] +happens on the [discussion mailing list][discuss-list], +which everyone is welcome to join. +You can also [reach us by email][contact]. + +[contact]: mailto:admin@software-carpentry.org +[dc-issues]: https://github.com/issues?q=user%3Adatacarpentry +[dc-lessons]: http://datacarpentry.org/lessons/ +[dc-site]: http://datacarpentry.org/ +[discuss-list]: http://lists.software-carpentry.org/listinfo/discuss +[github]: http://github.com +[github-flow]: https://guides.github.com/introduction/flow/ +[github-join]: https://github.com/join +[how-contribute]: https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github +[issues]: https://github.com/swcarpentry/shell-novice/issues/ +[repo]: https://github.com/swcarpentry/shell-novice/ +[swc-issues]: https://github.com/issues?q=user%3Aswcarpentry +[swc-lessons]: http://software-carpentry.org/lessons/ +[swc-site]: http://software-carpentry.org/ diff --git a/locale/fr/LICENSE.md b/locale/fr/LICENSE.md new file mode 100644 index 000000000..696cc3ae1 --- /dev/null +++ b/locale/fr/LICENSE.md @@ -0,0 +1,82 @@ +--- +title: Licenses +--- + +## Instructional Material + +All Software Carpentry, Data Carpentry, and Library Carpentry instructional material is +made available under the [Creative Commons Attribution +license][cc-by-human]. The following is a human-readable summary of +(and not a substitute for) the [full legal text of the CC BY 4.0 +license][cc-by-legal]. + +You are free: + +- to **Share**---copy and redistribute the material in any medium or format +- to **Adapt**---remix, transform, and build upon the material + +for any purpose, even commercially. + +The licensor cannot revoke these freedoms as long as you follow the +license terms. + +Under the following terms: + +- **Attribution**---You must give appropriate credit (mentioning that + your work is derived from work that is Copyright © Software + Carpentry and, where practical, linking to + http\://software-carpentry.org/), provide a [link to the + license][cc-by-human], and indicate if changes were made. You may do + so in any reasonable manner, but not in any way that suggests the + licensor endorses you or your use. + +**No additional restrictions**---You may not apply legal terms or +technological measures that legally restrict others from doing +anything the license permits. With the understanding that: + +Notices: + +- You do not have to comply with the license for elements of the + material in the public domain or where your use is permitted by an + applicable exception or limitation. +- No warranties are given. The license may not give you all of the + permissions necessary for your intended use. For example, other + rights such as publicity, privacy, or moral rights may limit how you + use the material. + +## Software + +Except where otherwise noted, the example programs and other software +provided by Software Carpentry and Data Carpentry are made available under the +[OSI][osi]-approved +[MIT license][mit-license]. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +## Trademark + +"Software Carpentry" and "Data Carpentry" and their respective logos +are registered trademarks of [Community Initiatives][ci]. + +[cc-by-human]: https://creativecommons.org/licenses/by/4.0/ +[cc-by-legal]: https://creativecommons.org/licenses/by/4.0/legalcode +[mit-license]: https://opensource.org/licenses/mit-license.html +[ci]: http://communityin.org/ +[osi]: https://opensource.org diff --git a/locale/fr/README.md b/locale/fr/README.md new file mode 100644 index 000000000..d613c95b7 --- /dev/null +++ b/locale/fr/README.md @@ -0,0 +1,61 @@ +# Introduction à l'analyse des données génomiques avec R et Bioconductor + +Contribution + +## Contributing + +Toutes les contributions visant à améliorer la leçon sont les bienvenues! Les responsables de la maintenance feront de leur mieux pour vous aider si vous avez des questions, des préoccupations ou si vous rencontrez des difficultés en cours de route. + +Nous vous invitons à vous familiariser avec notre guide de contribution et à consulter les directives plus détaillées concernant le formatage, les moyens de rendre la leçon localement, et même la manière d'écrire de nouveaux épisodes. + +Veuillez consulter la liste actuelle des [issues][FIXME] pour les idées de contribution à ce dépôt. Pour apporter votre contribution, nous utilisons le flux. Pour apporter votre contribution, utilisez GitHub, qui est bien expliqué dans le chapitre [Contribuer à un projet dans Pro Git par Scott Chacon.]. + +Recherchez l'étiquette "bonne première question/problème". Cela indique que la responsable accueillera favorablement une demande de répondre a la question ou problème. This +indicates that the maintainers will welcome a pull request fixing this +issue. + +## Liens utiles + +- Si vous développez pour la première fois du matériel pédagogique selon nos principes de conception, nous vous invitons à lire le Manuel de développement des programmes d'études de Carpentries. +- Consultez le site web de l'exemple de leçon pour en savoir plus sur l'utilisation du modèle de leçon. + +## Lesson team + +This lesson has been developed and is current maintained by + +- Laurent Gatto (maintainer) +- Charlotte Soneson +- Jenny Drnevich +- Robert Castelo +- Kevin Rue-Albert + +We would also like to acknowledge the contributions of: + +- Oliver Crook, Sarah Kaspar, Nick Hirschmueller, Lisa Breckels and Maria Doyle for their contributions during the Bioconductor introduction workshop in Heidelberg, as part of EuroBioc2021 |> 2022. +- Axelle Loriot, Marco Chiapelle, Manon Martin and Toby Hodges for various contributions and discussions. +- lmsimp, alorot, manonmartin, mchiapello, stavares843, JennyZadeh, csdaw, ninja-1337, fursham-h, lagerratrobe, fmichonneau, federicomarini, tobyhodges for pull requests. + +If we have contributed but we missed you, apologies, and feel free to add yourself with a PR. + +## Authors + +A list of contributors to the lesson can be found in [AUTHORS](AUTHORS) + +## Citation + +To cite this lesson, please consult with [CITATION](CITATION) + +[lesson-example]: https://carpentries.github.io/lesson-example +[cdh]: https://cdh.carpentries.org + +## Testing locally + +To test locally, run the following in the lessons directory: + +```r +sandpaper::serve() +``` + +For more details, see the [workbench installation +instructions](https://carpentries.github.io/workbench/#installation]. + diff --git a/locale/fr/config.yaml b/locale/fr/config.yaml new file mode 100644 index 000000000..204cb59c5 --- /dev/null +++ b/locale/fr/config.yaml @@ -0,0 +1,61 @@ +#------------------------------------------------------------ +#Values for this lesson. +#------------------------------------------------------------ +#Which carpentry is this (swc, dc, lc, or cp)? +#swc: Software Carpentry +#dc: Data Carpentry +#lc: Library Carpentry +#cp: Carpentries (to use for instructor training for instance) +#incubator: The Carpentries Incubator +carpentry: 'incubator' +#Overall title for pages. +title: 'Introduction to data analysis with R and Bioconductor' +#Date the lesson was created (YYYY-MM-DD, this is empty by default) +created: '2020-09-14' +#Comma-separated list of keywords for the lesson +keywords: 'software, data, lesson, The Carpentries' +#Life cycle stage of the lesson +#possible values: pre-alpha, alpha, beta, stable +life_cycle: 'stable' +#License of the lesson +license: 'CC-BY 4.0' +#Link to the source repository for this lesson +source: 'https://github.com/carpentries-incubator/bioc-intro' +#Default branch of your lesson +branch: 'main' +#Who to contact if there are any issues +contact: 'laurent.gatto@uclouvain.be' +#Navigation ------------------------------------------------ +#Use the following menu items to specify the order of +#individual pages in each dropdown section. Leave blank to +#include all pages in the folder. +#Example ------------- +#episodes: +#- introduction.md +#- first-steps.md +#learners: +#- setup.md +#instructors: +#- instructor-notes.md +#profiles: +#- one-learner.md +#- another-learner.md +#Order of episodes in your lesson +episodes: + - 10-data-organisation.Rmd + - 20-r-rstudio.Rmd + - 23-starting-with-r.Rmd + - 25-starting-with-data.Rmd + - 30-dplyr.Rmd + - 40-visualization.Rmd + - 60-next-steps.Rmd +#Information for Learners +learners: +#Information for Instructors +instructors: +#Learner Profiles +profiles: +#Customisation --------------------------------------------- +#This space below is where custom yaml items (e.g. pinning +#sandpaper and varnish versions) should live +url: 'https://carpentries-incubator.github.io/bioc-intro' diff --git a/locale/fr/episodes/10-data-organisation.Rmd b/locale/fr/episodes/10-data-organisation.Rmd new file mode 100644 index 000000000..458bf2158 --- /dev/null +++ b/locale/fr/episodes/10-data-organisation.Rmd @@ -0,0 +1,828 @@ +--- +source: Rmd +title: Organisation des données avec des feuilles de calcul +teaching: 30 +exercises: 30 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Découvrez les feuilles de calcul, leurs forces et leurs faiblesses. +- Comment formater les données dans des feuilles de calcul pour une utilisation efficace des données ? +- Découvrez les erreurs courantes des feuilles de calcul et comment les corriger. +- Organisez vos données selon des principes de données propres. +- Découvrez les formats de feuilles de calcul textuels tels que les formats séparés par des virgules (CSV) ou par des tabulations (TSV). + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- Comment organiser des données tabulaires ? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +> Cet épisode est basé sur la leçon _Analyse des données et +> Visualisation dans R pour les écologistes_ de Data Carpentries. + +## Tableurs + +**Question** + +- Quels sont les principes de base d'utilisation des feuilles de calcul pour une bonne organisation des données +  ? + +**Objectifs** + +- Décrire les bonnes pratiques pour organiser les données afin que les ordinateurs puissent en faire + la meilleure utilisation. + +**Point clé** + +- Une bonne organisation des données est la base de tout projet de recherche. + +Une bonne organisation des données est la base de votre projet de recherche +. La plupart des chercheurs disposent de données ou effectuent la saisie de données dans des feuilles de calcul +. Les tableurs sont des interfaces graphiques +très utiles pour concevoir des tableaux de données et gérer des fonctions de contrôle qualité +de données très basiques. Voir aussi @Broman : 2018. + +### Aperçu de la feuille de calcul + +Les feuilles de calcul sont utiles pour la saisie de données. Nous avons donc beaucoup de données +dans des feuilles de calcul. Une grande partie de votre temps en tant que chercheur sera consacrée à +cette étape de « gestion des données ». Ce n'est pas le plus amusant, mais c'est +nécessaire. Nous vous apprendrons comment réfléchir à l'organisation des données et +quelques pratiques pour une gestion plus efficace des données. + +### Ce que cette leçon ne vous apprendra pas + +- Comment faire des _statistiques_ dans une feuille de calcul +- Comment faire un _traçage_ dans une feuille de calcul +- Comment _écrire du code_ dans des tableurs + +Si vous cherchez à faire cela, une bonne référence est Head First +Excel, +publié par O'Reilly. + +### Pourquoi n'enseignons-nous pas l'analyse des données dans des feuilles de calcul + +- L'analyse des données dans des feuilles de calcul nécessite généralement beaucoup de + travail manuel. Si vous souhaitez modifier un paramètre ou exécuter une analyse avec un nouvel ensemble de données + , vous devez généralement tout refaire à la main. (Nous + savons que vous pouvez créer des macros, mais voyez le point suivant.) + +- Il est également difficile de suivre ou de reproduire des analyses statistiques ou graphiques + effectuées dans des tableurs lorsque vous souhaitez revenir à + votre travail ou que quelqu'un vous demande des détails sur votre analyse. + +De nombreux tableurs sont disponibles. Étant donné que la plupart des participants +utilisent Excel comme tableur principal, cette leçon +utilisera des exemples Excel. Un tableur gratuit qui peut également +être utilisé est LibreOffice. Les commandes peuvent différer un peu selon les programmes, +mais l'idée générale est la même. + +Les tableurs englobent de nombreuses choses que nous devons pouvoir +faire en tant que chercheurs. Nous pouvons les utiliser pour : + +- La saisie des données +- Organisation des données +- Sous-ensemble et tri des données +- Statistiques +- Traçage + +Les tableurs utilisent des tableaux pour représenter et afficher les données. Les données +formatées sous forme de tableaux sont également le thème principal de ce chapitre, et nous +verrons comment organiser les données en tableaux de manière standardisée pour +assurer une analyse efficace en aval. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi : Discutez des points suivants avec votre voisin + +- Avez-vous utilisé des feuilles de calcul, dans vos recherches, vos cours, + ou à la maison ? +- Quel type d’opérations effectuez-vous dans des feuilles de calcul ? +- Selon vous, pour lesquels les feuilles de calcul sont-elles utiles ? +- Avez-vous accidentellement fait quelque chose dans un tableur qui vous a rendu + frustré ou triste ? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +### Problèmes avec les feuilles de calcul + +Les feuilles de calcul sont utiles pour la saisie de données, mais en réalité, nous avons tendance à +utiliser des tableurs pour bien plus que la saisie de données. Nous les utilisons +pour créer des tableaux de données pour les publications, pour générer des statistiques récapitulatives +et réaliser des chiffres. + +Générer des tableaux pour des publications dans une feuille de calcul n'est pas +optimal - souvent, lors du formatage d'un tableau de données, nous +rapportons les principales statistiques récapitulatives d'une manière qui n'est pas vraiment destinée à être lue comme des données, et implique souvent un formatage spécial +(fusion de cellules, création de bordures, préférences esthétiques pour les couleurs, etc.). Nous vous conseillons de +effectuer ce genre d'opération au sein de votre logiciel d'édition de documents. + +Ces deux dernières applications, génératrices de statistiques et de chiffres, doivent +être utilisées avec précaution : en raison de la nature graphique, par glisser-déposer des +tableurs, il peut être très difficile, voire impossible, de +reproduisez vos pas (et encore moins retracer ceux de quelqu'un d'autre), en particulier si vos +statistiques ou chiffres nécessitent que vous fassiez des calculs plus complexes. De plus, +en effectuant des calculs dans une feuille de calcul, il est facile d'appliquer accidentellement une +formule légèrement différente à plusieurs cellules adjacentes. Lorsque vous utilisez un programme de statistiques basé sur une ligne de commande +comme R ou SAS, il est pratiquement +impossible d'appliquer un calcul à une observation de votre ensemble de données +mais pas à une autre, sauf si vous le faites cela exprès. + +### Utiliser des feuilles de calcul pour la saisie et le nettoyage des données + +Dans cette leçon, nous supposerons que vous utilisez très probablement Excel comme +votre tableur principal - il en existe d'autres (gnumeric, Calc +d'OpenOffice), et leurs fonctionnalités sont similaires, mais Excel semble +est le programme le plus utilisé par les biologistes et les chercheurs biomédicaux. + +Dans cette leçon, nous allons parler de : + +1. Formatage des tableaux de données dans des feuilles de calcul +2. Problèmes de formatage +3. Exporter des données + +## Formatage des tableaux de données dans des feuilles de calcul + +**Des questions** + +- Comment formater les données dans des feuilles de calcul pour une utilisation efficace des données ? + +**Objectifs** + +- Décrire les meilleures pratiques pour la saisie et le formatage des données dans les feuilles de calcul + . + +- Appliquez les meilleures pratiques pour organiser les variables et les observations dans une feuille de calcul + . + +**Points clés** + +- Ne modifiez jamais vos données brutes. Faites toujours une copie avant d'apporter des + modifications. + +- Gardez une trace de toutes les étapes que vous suivez pour nettoyer vos données dans un fichier texte brut + . + +- Organisez vos données selon des principes de données ordonnés. + +L'erreur la plus courante est de traiter les tableurs comme des cahiers de laboratoire +, c'est-à-dire de s'appuyer sur le contexte, les notes dans la marge, la disposition spatiale +des données et des champs pour transmettre des informations. En tant qu'humains, nous pouvons +(généralement) interpréter ces choses, mais les ordinateurs ne voient pas les informations +de la même manière, et à moins que nous expliquions à l'ordinateur ce que chaque +signifie (et ça peut être dur !), il ne pourra pas voir comment +nos données s'emboîtent. + +En utilisant la puissance des ordinateurs, nous pouvons gérer et analyser les données de manière beaucoup +plus efficace et plus rapide, mais pour utiliser cette puissance, nous devons +configurer nos données pour que l'ordinateur puisse comprenez-le (et +les ordinateurs sont très littéraux). + +C'est pourquoi il est extrêmement important de mettre en place des tableaux +bien formatés dès le départ - avant même de commencer à saisir les données de votre toute première expérience préliminaire +. L’organisation des données est le fondement de +votre projet de recherche. Cela peut rendre plus facile ou plus difficile le travail avec +vos données tout au long de votre analyse, il vaut donc la peine de réfléchir au moment +où vous effectuez votre saisie de données ou configurez votre expérience. Vous pouvez +configurer les choses de différentes manières dans des feuilles de calcul, mais certains de ces +choix peuvent limiter votre capacité à travailler avec les données dans d'autres programmes +ou vous empêcher de- Dans 6 mois ou votre collaborateur travaillera avec +les données. + +**Remarque :** les meilleures mises en page/formats (ainsi que les logiciels et les interfaces +) pour la saisie et l'analyse des données peuvent être différentes. Il est +important d’en tenir compte, et idéalement d’automatiser la conversion +de l’un à l’autre. + +### Garder une trace de vos analyses + +Lorsque vous travaillez avec des feuilles de calcul, lors d'un nettoyage de données ou d'analyses +, il est très facile de vous retrouver avec une feuille de calcul qui semble très +différente de celle avec laquelle vous avez commencé. Afin de pouvoir +reproduire vos analyses ou comprendre ce que vous avez fait lorsqu'un évaluateur ou un +instructeur demande une analyse différente, vous devez + +- créez un nouveau fichier avec vos données nettoyées ou analysées. Ne modifiez pas + l'ensemble de données d'origine, sinon vous ne saurez jamais par où vous avez commencé ! + +- gardez une trace des étapes que vous avez suivies lors de votre nettoyage ou de votre analyse. Vous + devez suivre ces étapes comme vous le feriez pour n’importe quelle étape d’une expérience. Nous + vous recommandons de le faire dans un fichier texte brut stocké dans le même dossier + que le fichier de données. + +Ceci pourrait être un exemple de configuration de feuille de calcul : + +![](fig/spreadsheet-setup-updated.png) + +Mettez ces principes en pratique aujourd’hui lors de vos exercices. + +Bien que la gestion des versions soit hors de portée de ce cours, vous pouvez consulter la leçon +Menuiseries sur +['Git'](https://swcarpentry.github.io/git-novice/) pour découvrez comment +maintenir le **contrôle de version** sur vos données. Voir aussi ce blog +post pour un tutoriel rapide ou +@Perez-Riverol:2016 pour une approche plus orientée recherche cas d'utilisation. + +### Structuration des données dans des feuilles de calcul + +Les règles cardinales de l’utilisation des tableurs pour les données : + +1. Mettez toutes vos variables dans des colonnes - la chose que vous mesurez, + comme « poids » ou « température ». +2. Placez chaque observation dans sa propre rangée. +3. Ne combinez pas plusieurs informations dans une seule cellule. Parfois + cela semble être une chose, mais pensez que si c'est la seule façon + vous voudrez pouvoir utiliser ou trier ces données. +4. Laissez les données brutes brutes – ne les modifiez pas ! +5. Exportez les données nettoyées dans un format texte tel que le format CSV + (valeurs séparées par des virgules). Cela garantit que n’importe qui peut utiliser + les données et est requis par la plupart des référentiels de données. + +Par exemple, nous disposons de données provenant de patients ayant visité plusieurs +hôpitaux à Bruxelles, en Belgique. Ils ont enregistré la date de la visite, +l'hôpital, le sexe, le poids et le groupe sanguin des patients. + +Si nous devions garder une trace des données comme ceci : + +![](fig/multiple-info.png) + +le problème est que les groupes ABO et Rhésus sont dans la même colonne de type `Blood` +. Donc, s'ils voulaient examiner toutes les observations du groupe A +ou examiner les distributions de poids par groupe ABO, il serait difficile +de le faire en utilisant cette configuration de données. Si à la place nous mettions les groupes ABO et Rhésus +dans des colonnes différentes, vous voyez que ce serait beaucoup plus facile. + +![](fig/single-info.png) + +Une règle importante lors de la création d'une feuille de données est que les **colonnes sont +utilisées pour les variables** et les **lignes sont utilisées pour les observations** : + +- les colonnes sont des variables +- les lignes sont des observations +- les cellules sont des valeurs individuelles + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi : Nous allons prendre un ensemble de données désordonné et décrire comment nous allons le nettoyer. + +1. Téléchargez un ensemble de données désordonné en cliquant sur + [ici](https://github.com/UCLouvain-CBIO/WSBIM1207/raw/master/data/messy_covid.xlsx). + +2. Ouvrez les données dans un tableur. + +3. Vous pouvez voir qu'il y a deux onglets. Les données contiennent diverses + variables cliniques enregistrées dans divers hôpitaux bruxellois lors des + première et deuxième vagues de COVID-19 en 2020. Comme vous pouvez le constater, les données + ont été enregistrées différemment lors des vagues + de mars et novembre. Vous êtes désormais la personne en charge de ce projet et vous souhaitez que + puisse commencer à analyser les données. + +4. Avec la personne à côté de vous, identifiez ce qui ne va pas avec cette feuille de calcul + . Discutez également des étapes que vous devrez suivre pour nettoyer + les onglets de la première et de la deuxième vague, et pour les rassembler tous dans une seule feuille de calcul + . + +**Important :** N'oubliez pas notre premier conseil : pour créer un +nouveau fichier (ou onglet) pour les données nettoyées, ne modifiez jamais vos données +(brutes) d'origine. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +Après avoir effectué cet exercice, nous discuterons en groupe de ce qui n'allait pas +avec ces données et de la manière dont vous pourriez y remédier. + + + + + + + + + + + + + + + + + + + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi : Une fois que vous avez rangé les données, répondez aux questions suivantes : + +- Combien d’hommes et de femmes ont participé à l’étude ? +- Combien de types A, AB et B ont été testés ? +- Comme ci-dessus, mais sans tenir compte des échantillons contaminés ? +- Combien de Rhésus + et - ont été testés ? +- Combien de donneurs universels (O-) ont été testés ? +- Quel est le poids moyen des hommes AB ? +- Combien d’échantillons ont été testés dans les différents hôpitaux ? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +Une **excellente référence**, en particulier en ce qui concerne les scripts R +est l'article _Tidy Data_ @Wickham:2014. + +## Erreurs courantes dans les feuilles de calcul + +**Des questions** + +- Quels sont les défis courants liés au formatage des données dans les feuilles de calcul + et comment pouvons-nous les éviter ? + +**Objectifs** + +- Reconnaître et résoudre les problèmes courants de formatage des feuilles de calcul. + +**Points clés** + +- Évitez d'utiliser plusieurs tableaux dans une même feuille de calcul. +- Évitez de répartir les données sur plusieurs onglets. +- Enregistrez les zéros comme des zéros. +- Utilisez une valeur nulle appropriée pour enregistrer les données manquantes. +- N'utilisez pas de formatage pour transmettre des informations ou pour donner une jolie apparence à votre feuille de calcul. +- Placez les commentaires dans une colonne séparée. +- Enregistrez les unités dans les en-têtes de colonnes. +- Incluez une seule information dans une cellule. +- Évitez les espaces, les chiffres et les caractères spéciaux dans les en-têtes de colonnes. +- Évitez les caractères spéciaux dans vos données. +- Enregistrez les métadonnées dans un fichier texte brut séparé. + + + + + + + + + +Il y a quelques erreurs potentielles à surveiller dans vos propres données +ainsi que dans les données de vos collaborateurs ou d'Internet. Si vous êtes +conscient des erreurs et de l'effet négatif possible sur l'analyse des données +en aval et l'interprétation des résultats, cela pourrait vous motiver +ainsi que les membres de votre projet à essayer de les éviter. Apporter de petits changements +à la façon dont vous formatez vos données dans des feuilles de calcul peut avoir un grand +impact sur l'efficacité et la fiabilité en matière de nettoyage +et d'analyse des données. + +- [Utiliser plusieurs tables](#tables) +- [Utiliser plusieurs onglets](#tabs) +- [Ne pas remplir les zéros](#zéros) +- [Utilisation de valeurs nulles problématiques](#null) +- [Utiliser le formatage pour transmettre des informations](#formatting) +- [Utiliser le formatage pour rendre la fiche technique jolie](#formatting_pretty) +- [Placer des commentaires ou des unités dans des cellules](#unités) +- [Saisie de plusieurs informations dans une cellule](#info) +- [Utilisation de noms de champs problématiques](#field_name) +- [Utilisation de caractères spéciaux dans les données](#special) +- [Inclusion de métadonnées dans le tableau de données](#metadata) + +### Utilisation de plusieurs tables {#tables} + +Une stratégie courante consiste à créer plusieurs tableaux de données dans une seule feuille de calcul +. Cela perturbe l'ordinateur, alors ne faites pas ça ! Lorsque vous +créez plusieurs tableaux dans une même feuille de calcul, vous établissez de fausses +associations entre les éléments pour l'ordinateur, qui considère chaque ligne comme +une observation. Vous utilisez également potentiellement le même nom de champ à +plusieurs endroits, ce qui rendra plus difficile le nettoyage de vos données dans +un formulaire utilisable. L'exemple ci-dessous illustre le problème : + +![](fig/2_datasheet_example.jpg) + +Dans l'exemple ci-dessus, l'ordinateur verra (par exemple) la ligne 4 et +supposera que toutes les colonnes A-AF font référence au même échantillon. Cette ligne +représente en fait quatre échantillons distincts (échantillon 1 pour chacune des quatre +dates de collecte différentes - 29 mai, 12 juin, 19 juin et +26 juin), ainsi que quelques statistiques récapitulatives calculées (une moyenne (avr) +et une erreur type de mesure (SEM)) pour deux de ces +échantillons. D'autres lignes posent également problème. + +### Utiliser plusieurs onglets {#tabs} + +Mais qu’en est-il des onglets du classeur ? Cela semble être un moyen simple d'organiser les données +, n'est-ce pas ? Eh bien, oui et non. Lorsque vous créez des onglets supplémentaires, vous ne parvenez pas +à permettre à l'ordinateur de voir les connexions dans les données qui s'y trouvent (vous devez +introduire des fonctions spécifiques à l'application de feuille de calcul ou +des scripts pour garantir cette connexion). Supposons, par exemple, que vous aillez créé un +onglet séparé pour chaque jour où vous prenez une mesure. + +Ce n'est pas une bonne pratique pour deux raisons : + +1. vous êtes plus susceptible d'ajouter accidentellement des incohérences à vos données + si à chaque fois que vous prenez une mesure, vous commencez à enregistrer les données + dans un nouvel onglet, et + +2. même si vous parvenez à empêcher toute incohérence, vous vous ajoutez une étape supplémentaire avant même d'analyser les données car vous devrez combiner ces données en une seule table de données. Vous devrez indiquer explicitement à l'ordinateur comment + combiner les onglets - et si les onglets ne sont pas formatés de manière cohérente, vous + devrez peut-être même le faire manuellement. + +La prochaine fois que vous saisirez des données et que vous créerez un autre onglet +ou un autre tableau, demandez-vous si vous pourriez éviter d'ajouter cet onglet en ajoutant +une autre colonne à votre feuille de calcul d'origine. Nous avons utilisé plusieurs onglets dans +notre exemple de fichier de données désordonné, mais vous avez maintenant vu comment vous pouvez +réorganiser vos données pour les consolider entre les onglets. + +Votre fiche technique peut devenir très longue au cours de l'expérience +. Cela rend plus difficile la saisie des données si vous ne voyez pas vos en-têtes +en haut de la feuille de calcul. Mais ne répétez pas votre ligne d'en-tête +. Ceux-ci peuvent facilement être mélangés aux données, entraînant des problèmes +plus tard. Au lieu de cela, vous pouvez [geler les en-têtes de la colonne +](https://support.office.com/en-ca/article/Freeze-column-headings-for-easy-scrolling-57ccce0c-cf85-4725-9579 -c5d13106ca6a) +afin qu'ils restent visibles même lorsque vous disposez d'une feuille de calcul comportant plusieurs +lignes. + +### Ne pas remplir les zéros {#zeros} + +Il se peut que lorsque vous mesurez quelque chose, il s'agisse généralement d'un zéro, +, par exemple le nombre de fois qu'un lapin est observé dans l'enquête. Pourquoi s'embêter +à écrire le chiffre zéro dans cette colonne, alors qu'il s'agit principalement de zéros ? + +Cependant, il existe une différence entre un zéro et une cellule vide dans une feuille de calcul +. Pour l’ordinateur, un zéro est en réalité une donnée. Vous l'avez mesuré ou +compté. Une cellule vide signifie qu'elle n'a pas été mesurée et l'ordinateur +l'interprétera comme une valeur inconnue (également appelée valeur nulle +ou valeur manquante). + +Les feuilles de calcul ou les programmes statistiques interpréteront probablement mal +les cellules vides que vous envisagez d'être des zéros. En n'entrant pas la valeur de +votre observation, vous dites à votre ordinateur de représenter ces données +comme inconnues ou manquantes (nulles). Cela peut entraîner des problèmes lors des +calculs ou analyses ultérieurs. Par exemple, la moyenne d'un ensemble de nombres +qui comprend une seule valeur nulle est toujours nulle (car l'ordinateur +ne peut pas deviner la valeur des observations manquantes). Parce que +de cela, il est très important d'enregistrer les zéros comme des zéros et vraiment +les données manquantes comme des valeurs nulles. + +### Utilisation de valeurs nulles problématiques {#null} + +**Exemple** : utiliser -999 ou d'autres valeurs numériques (ou zéro) pour +représente les données manquantes. + +**Solutions**: + +Il existe plusieurs raisons pour lesquelles les valeurs nulles sont représentées différemment +dans un ensemble de données. Parfois, des valeurs nulles déroutantes sont automatiquement +enregistrées à partir de l'appareil de mesure. Si tel est le cas, vous ne pouvez pas +faire grand-chose, mais cela peut être résolu lors du nettoyage des données avec un outil +comme +[OpenRefine](https://www.datacarpentry .org/OpenRefine-ecology-lesson/) +avant analyse. D'autres fois, différentes valeurs nulles sont utilisées pour transmettre +différentes raisons pour lesquelles les données ne sont pas là. Il s'agit d'une +information importante à capturer, mais elle utilise en fait une seule colonne pour capturer +deux informations. Like for using formatting to convey +information it would be good here to create a new +column like 'data\_missing' and use that column to capture the +different reasons. + +Quelle que soit la raison, c'est un problème si des données inconnues ou manquantes sont +enregistrées comme -999, 999 ou 0. + +Many statistical programs will not recognise that these are intended +to represent missing (null) values. La façon dont ces valeurs sont interprétées +dépendra du logiciel que vous utilisez pour analyser vos données. Il est +essentiel d’utiliser un indicateur nul clairement défini et cohérent. + +Les blancs (la plupart des applications) et NA (pour R) sont de bons choix +. @White : 2013 explique les bons choix pour indiquer des valeurs nulles +pour différentes applications logicielles dans leur article : + +![](fig/3_white_table_1.jpg) + +### Utiliser le formatage pour transmettre des informations {#formatting} + +**Exemple** : mise en évidence des cellules, des lignes ou des colonnes qui doivent être +exclues d'une analyse, en laissant des lignes vides pour indiquer +séparations dans les données. + +![](fig/formatting.png) + +**Solution** : créez un nouveau champ pour coder les données qui doivent être +exclues. + +![](fig/good_formatting.png) + +### Utiliser le formatage pour rendre la fiche technique jolie {#formatting\_pretty} + +**Exemple** : fusion de cellules. + +**Solution** : Si vous ne faites pas attention, le formatage d'une feuille de calcul pour qu'elle soit plus +esthétiquement peut compromettre la capacité de votre ordinateur à voir les +associations dans les données. Les cellules fusionnées rendront vos données illisibles +par les logiciels de statistiques. Pensez à restructurer vos données de telle manière +que vous n'aurez pas besoin de fusionner des cellules pour organiser vos données. + +### Placer des commentaires ou des unités dans des cellules {#units} + +La plupart des logiciels d'analyse ne peuvent pas voir les commentaires Excel ou LibreOffice, et +serait dérouté par les commentaires placés dans vos cellules de données. Comme +décrit ci-dessus pour le formatage, créez un autre champ si vous devez +ajouter des notes aux cellules. De même, n'incluez pas d'unités dans les cellules : idéalement, +toutes les mesures que vous placez dans une colonne devraient être dans la même unité +, mais si pour une raison quelconque ce n'est pas le cas, créez un autre champ et +spécifient les unités dans lesquelles se trouve la cellule. + +### Saisir plusieurs informations dans une cellule {#info} + +**Exemple** : Enregistrement des groupes ABO et Rhésus dans une seule cellule, tels que A+, +B+, A-, ... + +**Solution** : N'incluez pas plus d'une information dans une cellule +. Cela limitera les façons dont vous pourrez analyser vos données. Si +vous avez besoin de ces deux mesures, concevez votre fiche technique pour inclure +ces informations. Par exemple, incluez une colonne pour le groupe ABO et +une pour le groupe Rhésus. + +### Utilisation de noms de champs problématiques {#field\_name} + +Choisissez des noms de champs descriptifs, mais veillez à ne pas inclure d'espaces, de chiffres +ou de caractères spéciaux de quelque nature que ce soit. Les espaces peuvent être +mal interprétés par les analyseurs qui utilisent des espaces comme délimiteurs et certains programmes +n'aiment pas les noms de champs qui sont des chaînes de texte commençant par +nombres. + +Les traits de soulignement (`_`) sont une bonne alternative aux espaces. Pensez à écrire les noms +en casse chameau (comme ceci : SampleFileName) pour améliorer la lisibilité de +. N'oubliez pas que les abréviations qui ont un sens pour le moment +ne seront peut-être pas si évidentes dans 6 mois, mais n'en faites pas trop avec des noms qui +sont excessivement longs. L'inclusion des unités dans les noms de champs évite +toute confusion et permet aux autres d'interpréter facilement vos champs. + +**Exemples** + +| Réputation | Bonne alternative | Éviter | +| ---------------------------------------------------------------------- | ------------------------------------------- | -------------------------------------------- | +| Max\_temp\_C | Température maximale | Température maximale (°C) | +| Précipitations\_mm | Précipitation | précm | +| Moyenne\_année\_croissance | Croissance annuelle moyenne | Croissance moyenne/an | +| sexe | sexe | H/F | +| poids | poids | w. | +| cellule\_type | Type de cellule | Type de cellule | +| Observation\_01 | première\_observation | 1er Obs. | + +### Utilisation de caractères spéciaux dans les données {#special} + +**Exemple** : Vous traitez votre tableur comme un traitement de texte +lorsque vous rédigez des notes, par exemple en copiant des données directement depuis Word ou +d'autres applications. + +**Solution** : Il s'agit d'une stratégie courante. Par exemple, lorsqu'ils écrivent +un texte plus long dans une cellule, les utilisateurs incluent souvent des sauts de ligne, des tirets cadratins, +, etc. dans leur feuille de calcul. De plus, lors de la copie de données à partir d'applications +telles que Word, le formatage et les caractères +non standard (tels que les guillemets alignés à gauche et à droite) sont +inclus. Lors de l'exportation de ces données dans un environnement de codage/statistique +ou dans une base de données relationnelle, des choses dangereuses peuvent se produire, +comme des lignes coupées en deux et des erreurs d'encodage générées. + +La meilleure pratique générale consiste à éviter d'ajouter des caractères tels que des nouvelles lignes, des tabulations +et des tabulations verticales. In other words, treat a text cell as if it +were a simple web form that can only contain text and spaces. + +### Inclusion de métadonnées dans le tableau de données {#metadata} + +**Exemple** : Vous ajoutez une légende en haut ou en bas de votre tableau de données +expliquant la signification des colonnes, les unités, les exceptions, etc. + +**Solution** : L'enregistrement des données sur vos données ("métadonnées") est +essentiel. You may be on intimate terms with your dataset while you +are collecting and analysing it, but the chances that you will still +remember that the variable "sglmemgp" means single member of group, +for example, or the exact algorithm you used to transform a variable +or create a derived one, after a few months, a year, or more are slim. + +De plus, il existe de nombreuses raisons pour lesquelles d'autres personnes pourraient vouloir examiner ou +utiliser vos données : pour comprendre vos conclusions, pour vérifier vos conclusions, +pour examiner la publication que vous avez soumise, pour reproduire vos résultats, pour +concevoir une étude similaire, ou même archiver vos données pour y accéder et +réutiliser par d'autres. Bien que les données numériques soient par définition +lisibles par machine, comprendre leur signification est un travail pour les +êtres humains. L'importance de documenter vos données pendant la phase de collecte +et d'analyse de votre recherche ne peut être surestimée, +surtout si votre recherche doit faire partie du dossier scientifique +. + +Cependant, les métadonnées ne doivent pas être contenues dans le fichier de données +lui-même. Contrairement à un tableau dans un article ou un fichier supplémentaire, les métadonnées (sous +sous forme de légendes) ne doivent pas être incluses dans un fichier de données puisque ces +informations ne sont pas des données, et leur inclusion peut perturber la façon dont les programmes informatiques +interprètent votre fichier de données. Les métadonnées doivent plutôt être stockées +en tant que fichier distinct dans le même répertoire que votre fichier de données, de préférence +au format texte brut avec un nom qui l'associe clairement à votre +fichier de données. . Because metadata files are free text format, they also +allow you to encode comments, units, information about how null values +are encoded, etc. that are important to document but can disrupt the +formatting of your data file. + +De plus, les métadonnées au niveau du fichier ou de la base de données décrivent comment les fichiers qui +constituent l'ensemble de données sont liés les uns aux autres ; dans quel format ils se trouvent ; et +s'ils remplacent ou sont remplacés par les fichiers précédents. Un fichier readme.txt au niveau du dossier +est la manière classique de comptabiliser tous les +fichiers et dossiers d'un projet. + +(Texte sur les métadonnées adapté du cours en ligne Research Data +[MANTRA](https://datalib.edina.ac.uk/mantra) par EDINA et Data Library, +Université d'Édimbourg. MANTRA est sous licence Creative Commons +Attribution 4.0 International +Licence.) + +## Exporter des données + +**Question** + +- Comment pouvons-nous exporter des données à partir de feuilles de calcul d'une manière utile pour + les applications en aval ? + +**Objectifs** + +- Stockez les données des feuilles de calcul dans des formats de fichiers universels. +- Exportez les données d'une feuille de calcul vers un fichier CSV. + +**Points clés** + +- Les données stockées dans des formats de feuilles de calcul courants ne seront souvent pas lues + correctement dans un logiciel d'analyse de données, introduisant des erreurs dans vos données + . + +- L'exportation de données à partir de feuilles de calcul vers des formats tels que CSV ou TSV les place + dans un format qui peut être utilisé de manière cohérente par la plupart des programmes. + +Le stockage des données avec lesquelles vous allez travailler pour vos analyses dans le format de fichier Excel +par défaut (`*.xls` ou `*.xlsx` - selon la version d'Excel +) n'est pas une bonne idée. Pourquoi? + +- Parce qu'il s'agit d'un format propriétaire, et qu'il est possible que dans le + futur, la technologie n'existe pas (ou devienne suffisamment rare) pour + rendre l'ouverture du fichier peu pratique, voire impossible. déposer. + +- D'autres logiciels de tableur peuvent ne pas être en mesure d'ouvrir les fichiers enregistrés dans un format Excel propriétaire + . + +- Différentes versions d'Excel peuvent gérer les données différemment, entraînant + des incohérences. [Dates](https://datacarpentry.org/spreadsheet-ecology-lesson/03-dates-as-data/index.html) + est un exemple bien documenté d'incohérences dans le stockage de données. + +- Enfin, de plus en plus de revues et d'organismes subventionnaires vous demandent de + déposer vos données dans un référentiel de données, et la plupart d'entre elles n'acceptent pas + le format Excel. Il doit être dans l’un des formats discutés + ci-dessous. + +- Les points ci-dessus s'appliquent également à d'autres formats tels que les formats open data + utilisés par LibreOffice / Open Office. Ces formats ne sont pas + statiques et ne sont pas analysés de la même manière par différents packages logiciels + . + +Le stockage des données dans un format universel, ouvert et statique aidera à résoudre +ce problème. Essayez les valeurs délimitées par des tabulations (valeurs séparées par des tabulations ou TSV) ou +délimitées par des virgules (valeurs séparées par des virgules ou CSV). Les fichiers CSV sont des fichiers texte simples +où les colonnes sont séparées par des virgules, d'où « valeurs séparées par des virgules +» ou CSV. L'avantage d'un fichier CSV par rapport à un +Excel/SPSS/etc. est que nous pouvons ouvrir et lire un fichier CSV en utilisant +à peu près n'importe quel logiciel, y compris des éditeurs de texte brut comme TextEdit ou +NotePad. Les données d'un fichier CSV peuvent également être facilement importées dans d'autres +formats et environnements, tels que SQLite et R. Nous ne sommes pas liés à une +certaine version d'un certain programme coûteux lorsque nous travaillons avec CSV +fichiers, c'est donc un bon format avec lequel travailler pour une portabilité maximale et une +endurance. La plupart des tableurs peuvent facilement enregistrer au format texte délimité +comme CSV, bien qu'ils puissent vous avertir lors de +l'exportation du fichier. + +Pour enregistrer un fichier que vous avez ouvert dans Excel au format CSV : + +1. Dans le menu supérieur, sélectionnez « Fichier » et « Enregistrer sous ». +2. Dans le champ « Format », dans la liste, sélectionnez « Valeurs séparées par des virgules + » (`*.csv`). +3. Vérifiez le nom du fichier et l'emplacement où vous souhaitez l'enregistrer + et cliquez sur « Enregistrer ». + +Une remarque importante pour la rétrocompatibilité : vous pouvez ouvrir les fichiers CSV +dans Excel ! + +```{r, results="markup", fig.cap="Saving an Excel file to CSV.", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/excel-to-csv.png") +``` + +**Une note sur R et `xls`** : Il existe des packages R qui peuvent lire les fichiers `xls` +(ainsi que les feuilles de calcul Google). Il est même possible d'accéder à +différentes feuilles de calcul dans les documents `xls`. + +**Mais** + +- certains d'entre eux ne fonctionnent que sous Windows. +- cela équivaut à remplacer une exportation (simple mais manuelle) vers `csv` par + complexité/dépendances supplémentaires dans le code R d'analyse des données. +- Les meilleures pratiques en matière de formatage des données s’appliquent toujours. +- Y a-t-il vraiment une bonne raison pour laquelle `csv` (ou similaire) n'est pas + adéquat ? + +### Mises en garde concernant les virgules + +Dans certains ensembles de données, les valeurs des données elles-mêmes peuvent inclure des virgules +(,). Dans ce cas, le logiciel que vous utilisez (y compris Excel) +affichera très probablement de manière incorrecte les données en colonnes. En effet, +les virgules qui font partie des valeurs de données seront interprétées comme des délimiteurs +. + +Par exemple, nos données pourraient ressembler à ceci : + +``` +species_id,genus,species,taxa +AB,Amphispiza,bilineata,Bird +AH,Ammospermophilus,harrisi,Rodent, not censused +AS,Ammodramus,savannarum,Bird +BA,Baiomys,taylori,Rodent +``` + +Dans l'enregistrement « AH, Ammospermophilus, harrisi, Rongeur, non recensé », la valeur +pour « taxons » comprend une virgule (« Rongeur, non recensé »). Si nous essayons +de lire ce qui précède dans Excel (ou un autre tableur), nous obtiendrons +quelque chose comme ceci : + +```{r, results="markup", fig.cap="The risks of having commas inside comma-separated data.", echo=FALSE, purl=FALSE, out.width="80%", fig.align="center"} +knitr::include_graphics("fig/csv-mistake.png") +``` + +La valeur de « taxons » a été divisée en deux colonnes (au lieu d'être placée +dans une seule colonne « D »). Cela peut se propager à un certain nombre d'autres erreurs +. Par exemple, la colonne supplémentaire sera interprétée comme une colonne +avec de nombreuses valeurs manquantes (et sans en-tête approprié). En plus de +cela, la valeur dans la colonne « D » pour l'enregistrement de la ligne 3 (donc celle +où la valeur de « taxons » contenait la virgule) est désormais incorrecte. + +Si vous souhaitez stocker vos données au format `csv` et vous attendez à ce que vos valeurs de données +contiennent des virgules, vous pouvez éviter le problème évoqué +ci-dessus en mettant les valeurs entre guillemets (""). En appliquant cette règle, nos données +pourraient ressembler à ceci : + +``` +species_id,genus,species,taxa +"AB","Amphispiza","bilineata","Bird" +"AH","Ammospermophilus","harrisi","Rodent, not censused" +"AS","Ammodramus","savannarum","Bird" +"BA","Baiomys","taylori","Rodent" +``` + +Désormais, l'ouverture de ce fichier en tant que « csv » dans Excel n'entraînera pas une colonne +supplémentaire, car Excel n'utilisera que des virgules qui se trouvent en dehors des guillemets +comme caractères de délimitation. + +Alternativement, si vous travaillez avec des données contenant des virgules, vous devrez probablement +utiliser un autre délimiteur lorsque vous travaillerez dans une feuille de calcul +[^decsep]. Dans ce cas, pensez à utiliser des tabulations comme délimiteur et +à travailler avec des fichiers TSV. Les fichiers TSV peuvent être exportés à partir de feuilles de calcul +de la même manière que les fichiers CSV. + +[^decsep]: Ceci est particulièrement pertinent dans les pays européens + où la virgule est utilisée comme séparateur décimal + . Dans de tels cas, le séparateur de valeurs par défaut dans un fichier csv + sera le point-virgule (;), ou les valeurs seront systématiquement + entre guillemets. + +Si vous travaillez avec un ensemble de données déjà existant dans lequel les valeurs de données +ne sont pas incluses entre "" mais qui ont à la fois des virgules comme délimiteurs +et des parties de valeurs de données, vous êtes potentiellement confronté à un problème majeur. +avec nettoyage des données. Si l'ensemble de données que vous traitez contient +des centaines ou des milliers d'enregistrements, nettoyez-les manuellement (soit en +supprimant les virgules des valeurs de données, soit en mettant les valeurs entre +guillemets - "") non seulement va prendre des heures et des heures, mais peut +finir par vous amener à introduire accidentellement de nombreuses erreurs. + +Le nettoyage des ensembles de données est l’un des problèmes majeurs dans de nombreuses disciplines scientifiques +. L’approche dépend presque toujours du contexte +particulier. Cependant, il est recommandé de nettoyer les données de manière +automatisée, par exemple en écrivant et en exécutant un script. Les leçons +Python et R vous donneront les bases pour développer des compétences permettant de +créer des scripts pertinents. + +## Résumé + +```{r analysis, results="asis", fig.margin=TRUE, fig.cap="A typical data analysis workflow.", fig.width=7, fig.height=4, echo=FALSE, purl=FALSE} +knitr::include_graphics("fig/analysis.png") +``` + +Un flux de travail typique d'analyse de données est illustré dans la figure ci-dessus, +où les données sont transformées, visualisées et modélisées à plusieurs reprises. Cette itération +est répétée plusieurs fois jusqu'à ce que les données soient comprises. Cependant, dans +de nombreux cas réels, la plupart du temps est consacré au nettoyage et +à la préparation des données, plutôt qu'à leur analyse et à leur compréhension +. + +An agile data analysis workflow, with several fast iterations of the +transform/visualise/model cycle is only feasible if the data is +formatted in a predictable way and one can reason about the data +without having to look at it and/or fix it. + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Une bonne organisation des données est la base de tout projet de recherche. + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/fr/episodes/20-r-rstudio.Rmd b/locale/fr/episodes/20-r-rstudio.Rmd new file mode 100644 index 000000000..e128e1bf7 --- /dev/null +++ b/locale/fr/episodes/20-r-rstudio.Rmd @@ -0,0 +1,667 @@ +--- +source: Rmd +title: R et RStudio +teaching: 30 +exercises: 0 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Décrivez l'objectif des volets RStudio Script, Console, Environment et Plots. +- Organisez les fichiers et les répertoires pour un ensemble d'analyses en tant que projet R et comprenez le but du répertoire de travail. +- Utilisez l'interface d'aide intégrée de RStudio pour rechercher plus d'informations sur les fonctions R. +- Montrez comment fournir suffisamment d’informations pour le dépannage avec la communauté des utilisateurs R. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- Que sont R et RStudio ? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +> Cet épisode est basé sur la leçon _Analyse des données et +> Visualisation dans R pour les écologistes_ de Data Carpentries. + +## Qu’est-ce que R ? Qu’est-ce que RStudio ? + +Le terme [R](https://www.r-project.org/) est utilisé pour désigner le +_langage de programmation_, l'_environnement de calcul statistique_ +et _le logiciel_ qui interprète les scripts écrits à l'aide de celui-ci. + +[RStudio](https://rstudio.com) est actuellement un moyen très populaire non seulement +d'écrire vos scripts R mais aussi d'interagir avec le logiciel R +[^plainr]. Pour fonctionner correctement, RStudio a besoin de R et +donc les deux doivent être installés sur votre ordinateur. + +[^plainr]: Au lieu d'utiliser R directement depuis la console de ligne de commande + . Il existe d'autres logiciels qui s'interfacent et intègrent + avec R, mais RStudio est particulièrement bien adapté aux débutants + tout en proposant de nombreuses fonctionnalités très avancées. + +La RStudio IDE Cheat +Sheet +fournit beaucoup plus d'informations que ce qui sera couvert ici, mais peut être +utile pour apprendre les raccourcis clavier et découvrir de nouvelles fonctionnalités. + +## Pourquoi apprendre R ? + +### R n'implique pas beaucoup de pointage et de clic, et c'est une bonne chose + +The learning curve might be steeper than with other software, but with +R, the results of your analysis do not rely on remembering a +succession of pointing and clicking, but instead on a series of +written commands, and that's a good thing! Ainsi, si vous souhaitez refaire +votre analyse parce que vous avez collecté plus de données, vous n'avez pas besoin de +vous rappeler sur quel bouton vous avez cliqué dans quel ordre pour obtenir vos +résultats ; il vous suffit de réexécuter votre script. + +Travailler avec des scripts rend les étapes que vous avez utilisées dans votre analyse claires, +et le code que vous écrivez peut être inspecté par quelqu'un d'autre qui peut vous donner +des commentaires et repérer les erreurs. + +Travailler avec des scripts vous oblige à avoir une compréhension plus profonde de ce que +vous faites et facilite votre apprentissage et votre compréhension des méthodes +que vous utilisez. + +### Le code R est idéal pour la reproductibilité + +La reproductibilité signifie que quelqu'un d'autre (y compris votre futur moi) peut +obtenir les mêmes résultats à partir du même ensemble de données en utilisant le même code d'analyse +. + +R s'intègre à d'autres outils pour générer des manuscrits ou des rapports à partir de votre code +. Si vous collectez plus de données ou corrigez une erreur dans votre ensemble de données, les chiffres +et les tests statistiques de votre manuscrit ou rapport sont mis à jour +automatiquement. + +Un nombre croissant de revues et d'agences de financement s'attendent à ce que les analyses +soient reproductibles, donc connaître R vous donnera un avantage avec ces +exigences. + +### R est interdisciplinaire et extensible + +Avec plus de 10 000 packages[^whatarepkgs] pouvant être installés pour étendre ses +capacités, R fournit un cadre qui vous permet de combiner +des approches statistiques de nombreuses disciplines scientifiques pour s'adapter au mieux à +le cadre analytique dont vous avez besoin pour analyser vos données. Par exemple, +R propose des packages pour l'analyse d'images, le SIG, les séries chronologiques, la génétique +de population et bien plus encore. + +[^whatarepkgs]: c'est-à-dire des modules complémentaires qui confèrent à R de nouvelles fonctionnalités, + telles que l'analyse de données bioinformatiques. + +```{r, fig.cap="Exponential increase of the number of packages available on [CRAN](https://cran.r-project.org/), the Comprehensive R Archive Network. From the R Journal, Volume 10/2, December 2018.", echo=FALSE, message=FALSE} +knitr::include_graphics("fig/cran.png") +``` + +### R fonctionne sur des données de toutes formes et tailles + +Les compétences que vous apprenez avec R évoluent facilement avec la taille de votre ensemble de données +. Que votre ensemble de données comporte des centaines ou des millions de lignes, cela +ne fera pas beaucoup de différence pour vous. + +R est conçu pour l’analyse des données. Il est livré avec des structures de données spéciales +et des types de données qui facilitent la gestion des données manquantes et des facteurs statistiques +. + +R peut se connecter à des feuilles de calcul, des bases de données et à de nombreux autres formats de données, +sur votre ordinateur ou sur le Web. + +### R produit des graphiques de haute qualité + +Les fonctionnalités de traçage de R sont étendues et vous permettent d'ajuster +n'importe quel aspect de votre graphique pour transmettre le plus efficacement possible le message de +vos données. + +### R a une communauté nombreuse et accueillante + +Des milliers de personnes utilisent R quotidiennement. Beaucoup d'entre eux sont prêts à vous aider +via des listes de diffusion et des sites Web tels que Stack +Overflow, ou sur le RStudio +communauté. Ces larges communautés d'utilisateurs +s'étendent à des domaines spécialisés tels que la bioinformatique. L'un de ces sous-ensembles de la communauté R est [Bioconductor](https://bioconductor.org/), un projet scientifique pour l'analyse et la compréhension « des données provenant d'essais biologiques actuels et émergents ». Cet atelier a été développé par des membres de la communauté Bioconductor ; pour plus d'informations sur Bioconductor, veuillez consulter l'atelier complémentaire ["The Bioconductor Project"](https://carpentries-incubator.github.io/bioc-project/). + +### Non seulement R est gratuit, mais il est également open source et multiplateforme + +N'importe qui peut inspecter le code source pour voir comment R fonctionne. Grâce à cette +transparence, il y a moins de risques d'erreurs, et si vous (ou +quelqu'un d'autre) en trouvez, vous pouvez signaler et corriger des bugs. + +## Connaître RStudio + +Commençons par découvrir [RStudio](https://www.rstudio.com/), +qui est un environnement de développement intégré (IDE) permettant de travailler avec +R. + +Le produit open source RStudio IDE est gratuit sous la Affero General +Public License (AGPL) v3. +L'IDE RStudio est également disponible avec une licence commerciale et +une assistance prioritaire par courrier électronique de Posit, Inc. + +Nous utiliserons l'IDE RStudio pour écrire du code, parcourir les fichiers sur notre +ordinateur, inspecter les variables que nous allons créer et visualiser +les tracés que nous allons générer. RStudio peut également être utilisé pour d'autres choses +(par exemple, le contrôle de version, le développement de packages, l'écriture d'applications Shiny) que +nous n'aborderons pas pendant l'atelier. + +```{r, results="markup", fig.cap="RStudio interface screenshot. Clockwise from top left: Source, Environment/History, Files/Plots/Packages/Help/Viewer, Console.", echo=FALSE, purl=FALSE, out.width="100%", fig.align="center"} +knitr::include_graphics("fig/rstudio-screenshot.png") +``` + +La fenêtre RStudio est divisée en 4 "Volets" : + +- la **Source** de vos scripts et documents (en haut à gauche, dans la mise en page par défaut + ) +- votre **Environnement/Historique** (en haut à droite), +- vos **Fichiers/Tracés/Packages/Aide/Visionneuse** (en bas à droite), et +- la R **Console** (en bas à gauche). + +L'emplacement de ces volets et leur contenu peuvent être personnalisés (voir le menu +, `Outils -> Options globales -> Disposition des volets`). + +L'un des avantages de l'utilisation de RStudio est que toutes les informations dont vous +avez besoin pour écrire du code sont disponibles dans une seule fenêtre. De plus, avec +de nombreux raccourcis, la **complétion automatique** et la **mise en surbrillance** pour les principaux +types de fichiers que vous utilisez lors du développement dans R, RStudio facilitera la saisie de +et moins sujet aux erreurs. + +## Mise en place + +Il est recommandé de conserver un ensemble de données, d'analyses et de textes connexes +autonomes dans un seul dossier, appelé \*\*répertoire de travail +\*\*. Tous les scripts de ce dossier peuvent alors utiliser +**chemins relatifs** vers les fichiers qui indiquent où dans le projet se trouve un fichier +(par opposition aux chemins absolus, qui pointent vers l'endroit où se trouve un fichier +). +se trouve sur un ordinateur spécifique). Travailler de cette façon rend +beaucoup plus facile le déplacement de votre projet sur votre ordinateur et le partage avec +d'autres sans vous soucier de savoir si les scripts sous-jacents +fonctionneront toujours. + +RStudio fournit un ensemble d'outils utiles pour ce faire via son interface "Projets" +, qui non seulement crée un répertoire de travail pour vous, mais mémorise également +son emplacement (vous permettant d'y accéder rapidement ) et conserve éventuellement +les paramètres personnalisés et les fichiers ouverts pour faciliter la reprise du travail après une +pause. Suivez les étapes de création d'un "Projet R" pour ce tutoriel +ci-dessous. + +1. Démarrez RStudio. +2. Dans le menu « Fichier », cliquez sur « Nouveau projet ». Choisissez `Nouveau répertoire`, puis + `Nouveau projet`. +3. Entrez un nom pour ce nouveau dossier (ou "répertoire") et choisissez un + emplacement pratique pour celui-ci. Ce sera votre **répertoire de travail** + pour cette session (ou tout le cours) (par exemple, `bioc-intro`). +4. Cliquez sur « Créer un projet ». +5. (Facultatif) Définissez les préférences sur « Jamais » pour enregistrer l'espace de travail dans RStudio. + +Les préférences par défaut de RStudio fonctionnent généralement bien, mais enregistrer un espace de travail dans +.RData peut être fastidieux, surtout si vous travaillez avec des ensembles de données plus volumineux. +Pour désactiver cela, allez dans Outils --> « Options globales » et sélectionnez l'option « Jamais » +pour « Enregistrer l'espace de travail dans .RData » à la sortie. + +```{r, results="markup", fig.cap="Set 'Save workspace to .RData on exit' to 'Never'", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/rstudio-preferences.png") +``` + +Pour éviter les problèmes d'encodage des caractères entre Windows et d'autres +systèmes d'exploitation, nous allons +définir UTF-8 par défaut : + +```{r, results="markup", fig.cap="Set the default text encoding to UTF-8 to save us headache in the coming future. (Figure from the link above).", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/utf8.png") +``` + +### Organiser votre répertoire de travail + +L'utilisation d'une structure de dossiers cohérente dans vos projets aidera à garder les choses +organisées et facilitera également la recherche/le classement des éléments à l'avenir. Ce +peut être particulièrement utile lorsque vous avez plusieurs projets. En général, vous pouvez +créer des répertoires (dossiers) pour les **scripts**, **données** et **documents**. + +- **`data/`** Utilisez ce dossier pour stocker vos données brutes et les ensembles de données intermédiaires + que vous pouvez créer pour les besoins d'une analyse particulière. Par + par souci de transparence et de + [provenance](https://en.wikipedia.org/wiki/Provenance), vous devez + _toujours_ conserver une copie de votre données brutes accessibles et effectuez autant de + le nettoyage et le prétraitement de vos données par programme (c'est-à-dire avec + scripts, plutôt que manuellement) que possible. Séparer les données brutes + des données traitées est également une bonne idée. Par exemple, vous pourriez + avoir les fichiers `data/raw/tree_survey.plot1.txt` et `...plot2.txt` conservés + séparés d'un `data/processed/tree.survey. fichier csv` généré par + le script `scripts/01.preprocess.tree_survey.R`. +- **`documents/`** Ce serait un endroit pour conserver les plans, les brouillons, les + et d'autres textes. +- **`scripts/`** (ou `src`) Ce serait l'emplacement où conserver vos scripts R + pour différentes analyses ou traçages, et potentiellement un + dossier séparé pour vos fonctions (plus nous y reviendrons plus tard). + +Vous souhaiterez peut-être des répertoires ou sous-répertoires supplémentaires en fonction de +les besoins de votre projet, mais ceux-ci devraient constituer l'épine dorsale de votre répertoire de travail +. + +```{r, results="markup", fig.cap="Example of a working directory structure.", echo=FALSE, purl=FALSE, out.width="100%", fig.align="center"} +knitr::include_graphics("fig/working-directory-structure.png") +``` + +Pour ce cours, nous aurons besoin d'un dossier `data/` pour stocker nos données brutes, +et nous utiliserons `data_output/` lorsque nous apprendrons à exporter des données sous forme de +fichiers CSV, et Dossier `fig_output/` pour les figures que nous allons enregistrer. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi : créer la structure de répertoires de votre projet + +Sous l'onglet « Fichiers » à droite de l'écran, cliquez sur « Nouveau dossier » et +créez un dossier nommé « données » dans votre répertoire de travail nouvellement créé +(par exemple, « ~/bioc -intro/données`). (Vous pouvez également taper `dir.create("data")`sur +votre console R.) Répétez ces opérations pour créer un dossier`data_output/`et un`fig_output\`. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +Nous allons conserver le script à la racine de notre répertoire de travail +car nous n'allons utiliser qu'un seul fichier et cela rendra les choses +plus faciles. + +Votre répertoire de travail devrait maintenant ressembler à ceci : + +```{r, results="markup", fig.cap="How it should look like at the beginning of this lesson", echo=FALSE, purl=FALSE, out.width="100%", fig.align="center"} +knitr::include_graphics("fig/r-starting-how-it-should-look-like.png") +``` + +La **gestion de projet** s'applique également aux projets de bioinformatique, +bien sûr[^bioindatascience]. William Noble (@Noble:2009) propose la +structure de répertoires suivante : + +[^bioindatascience]: Dans ce cours, nous considérons la bioinformatique comme une + science des données appliquée aux données biologiques ou bio-médicales. + +> Les noms de répertoires sont en gros caractères et les noms de fichiers sont en caractères plus petits +> . Seul un sous-ensemble des fichiers est affiché ici. Notez que les dates +> sont formatées `--` afin qu'elles puissent être +> triées par ordre chronologique. Le code source `src/ms-analysis.c` +> est compilé pour créer `bin/ms-analysis` et est documenté dans +> `doc/ms-analysis.html`. Les fichiers `README` dans les répertoires de données +> précisent qui a téléchargé les fichiers de données à partir de quelle URL et à quelle date +> . Le script du pilote `results/2009-01-15/runall` +> génère automatiquement les trois sous-répertoires split1, split2 et split3, +> correspondant à trois divisions de validation croisée. Le script +> `bin/parse-sqt.py` est appelé par les deux scripts du pilote `runall` +> . + +```{r bioinfoproj, fig.cap="Directory structure for a sample bioinformatics project.", out.width="100%", echo=FALSE} +knitr::include_graphics("fig/noble-bioinfo-project.png") +``` + +L'aspect le plus important d'un répertoire de projet +bien défini et bien documenté est de permettre à quelqu'un qui n'est pas familier avec le projet +[^futureself] de + +1. comprendre en quoi consiste le projet, quelles données sont disponibles, quelles + analyses ont été effectuées et quels résultats ont été produits et, plus important encore, + +2. répétez l'analyse à nouveau - avec de nouvelles données ou en modifiant certains paramètres d'analyse + . + +[^futureself]: Cette personne pourrait être, et sera très probablement votre + futur moi, quelques mois ou années après que les analyses aient été + effectuées. + +### Le répertoire de travail + +Le répertoire de travail est un concept important à comprendre. C'est l'endroit +à partir duquel R recherchera et enregistrera les fichiers. Lorsque vous +écrivez du code pour votre projet, il doit faire référence à des fichiers en relation avec +la racine de votre répertoire de travail et n'a besoin que de fichiers au sein de cette structure +. + +L'utilisation de projets RStudio facilite cela et garantit que votre répertoire de travail +est correctement défini. Si vous avez besoin de le vérifier, vous pouvez utiliser +`getwd()`. If for some reason your working directory is not what it +should be, you can change it in the RStudio interface by navigating in +the file browser where your working directory should be, and clicking +on the blue gear icon `More`, and select `Set As Working Directory`. +Vous pouvez également utiliser `setwd("/path/to/working/directory")` pour +réinitialiser votre répertoire de travail. Cependant, vos scripts ne doivent pas inclure +cette ligne car elle échouera sur l'ordinateur de quelqu'un d'autre. + +**Exemple** + +Le schéma ci-dessous représente le répertoire de travail `bioc-intro` avec les sous-répertoires +`data` et `fig_output`, et 2 fichiers dans ce dernier : + +``` +bioc-intro/data/ + /fig_output/fig1.pdf + /fig_output/fig2.png +``` + +Si on était dans le répertoire de travail, on pourrait faire référence au fichier `fig1.pdf` +en utilisant le chemin relatif `bioc-intro/fig_output/fig1.pdf` ou le chemin absolu +`/ accueil/user/bioc-intro/fig_output/fig1.pdf`. + +Si nous étions dans le répertoire `data`, nous utiliserions le chemin relatif +`../fig_output/fig1.pdf` ou le même chemin absolu +`/home/user/bioc-intro /fig_output/fig1.pdf`. + +## Interagir avec R + +La base de la programmation est que nous écrivons les instructions que l'ordinateur +doit suivre, puis nous disons à l'ordinateur de suivre ces instructions +. Nous écrivons, ou _codeons_, des instructions dans R car c'est un +langage commun que l'ordinateur et nous pouvons comprendre. Nous appelons +les instructions _commandes_ et nous disons à l'ordinateur de suivre les instructions +en _exécutant_ (également appelé _exécutant_) ces commandes. + +Il existe deux manières principales d'interagir avec R : en utilisant la +**console** ou en utilisant des **scripts** (fichiers texte brut contenant +votre code). Le volet de la console (dans RStudio, le panneau inférieur gauche) est +l'endroit où les commandes écrites en langage R peuvent être saisies et +exécutées immédiatement par l'ordinateur. C'est également là que les résultats +seront affichés pour les commandes exécutées. Vous pouvez taper des commandes +directement dans la console et appuyer sur « Entrée » pour exécuter ces commandes +, mais elles seront oubliées lorsque vous fermerez la session. + +Parce que nous voulons que notre code et notre flux de travail soient reproductibles, il est préférable +de taper les commandes souhaitées dans l'éditeur de script et d'enregistrer le script +. De cette façon, il existe un enregistrement complet de ce que nous avons fait, et +n'importe qui (y compris notre futur moi !) peuvent facilement reproduire les résultats +sur leur ordinateur. Notez cependant que le simple fait de taper les commandes +dans le script ne les _exécute_ pas automatiquement - elles doivent quand même +être envoyées à la console pour exécution. + +RStudio vous permet d'exécuter des commandes directement depuis l'éditeur de script +en utilisant le raccourci `Ctrl` + `Entrée` (sur Mac, `Cmd` + `Return` +fonctionnera également). La commande sur la ligne actuelle du script (indiquée +par le curseur) ou toutes les commandes dans le texte actuellement sélectionné +seront envoyées à la console et exécutées lorsque vous appuyez sur `Ctrl` + +`Entrer`. Vous pouvez trouver d'autres raccourcis clavier dans cette aide-mémoire RStudio +sur l'IDE RStudio +. + +À un moment donné de votre analyse, vous souhaiterez peut-être vérifier le contenu d'une variable +ou la structure d'un objet, sans nécessairement en conserver un enregistrement +dans votre script. Vous pouvez taper ces commandes et les exécuter +directement dans la console. RStudio fournit les raccourcis `Ctrl` + `1` et +`Ctrl` + `2` vous permettant de passer entre le script et les volets de la console +. + +Si R est prêt à accepter les commandes, la console R affiche une invite `>`. If +it receives a command (by typing, copy-pasting or sending from the script +editor using `Ctrl` + `Enter`), R will try to execute it, and when +ready, will show the results and come back with a new `>` prompt to +wait for new commands. + +Si R attend toujours que vous saisissiez plus de données parce que +n'est pas encore terminé, la console affichera une invite « + ». Cela signifie que vous +n'avez pas fini de saisir une commande complète. This is because you have +not 'closed' a parenthesis or quotation, i.e. you don't have the same +number of left-parentheses as right-parentheses, or the same number of +opening and closing quotation marks. Lorsque cela se produit et que vous +pensez avoir fini de taper votre commande, cliquez dans la fenêtre +de la console et appuyez sur « Échap » ; cela annulera la commande incomplète et +vous ramènera à l'invite `>`. + +## Comment en savoir plus pendant et après le cours ? + +Le matériel que nous aborderons au cours de ce cours vous donnera un premier +aperçu de la façon dont vous pouvez utiliser R pour analyser des données pour votre propre +recherche. Cependant, vous devrez en apprendre davantage pour effectuer des +opérations avancées telles que nettoyer votre ensemble de données, utiliser des méthodes statistiques, +ou créer de superbes graphiques\[^dans ce cours]. La meilleure façon de devenir +compétent et efficace en R, comme avec tout autre outil, est de l'utiliser pour +répondre à vos questions de recherche réelles. En tant que débutant, il peut sembler +intimidant de devoir écrire un script à partir de zéro, et étant donné que de nombreuses +personnes rendent leur code disponible en ligne, modifiant le code existant pour +répondre à vos objectifs. cela pourrait vous permettre de démarrer plus facilement. + +[^inthiscoure]: Nous présenterons ici la plupart d'entre eux (sauf les statistiques) + , mais nous ne parviendrons qu'à effleurer la surface de la richesse de + ce qu'il est possible de faire avec R. + +```{r kitten, results="markup", echo=FALSE, purl=FALSE, out.width="400px", fig.align="center"} +knitr::include_graphics("fig/kitten-try-things.jpg") +``` + +## Cherche de l'aide + +### Utilisez l'interface d'aide intégrée de RStudio pour rechercher plus d'informations sur les fonctions R. + +```{r rstudiohelp, fig.cap="RStudio help interface.", results="markup", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/rstudiohelp.png") +``` + +L'un des moyens les plus rapides d'obtenir de l'aide consiste à utiliser l'interface d'aide RStudio +. Ce panneau par défaut se trouve dans le panneau inférieur droit +de RStudio. Comme le montre la capture d'écran, en tapant le mot +"Mean", RStudio essaie également de donner un certain nombre de suggestions qui pourraient vous intéresser +. La description s'affiche alors dans la fenêtre d'affichage +. + +### Je connais le nom de la fonction que je souhaite utiliser, mais je ne sais pas comment l'utiliser + +Si vous avez besoin d'aide avec une fonction spécifique, disons `barplot()`, vous +pouvez taper : + +```{r, eval=FALSE, purl=TRUE} +?barplot +``` + +Si vous avez juste besoin de vous rappeler les noms des arguments, vous pouvez utiliser : + +```{r, eval=FALSE, purl=TRUE} +args(lm) +``` + +### Je veux utiliser une fonction qui fait X, il doit y avoir une fonction pour ça mais je ne sais pas laquelle... + +Si vous recherchez une fonction pour effectuer une tâche particulière, vous pouvez utiliser la fonction +`help.search()`, qui est appelée par le double point d'interrogation `??`. +Cependant, cela ne recherche dans les packages installés que les pages d'aide avec une correspondance +avec votre demande de recherche. + +```{r, eval=FALSE, purl=TRUE} +??kruskal +``` + +Si vous ne trouvez pas ce que vous cherchez, vous pouvez utiliser +le site Web [rdocumentation.org](https://www.rdocumentation.org) qui recherche +dans les fichiers d'aide de tous les forfaits disponibles. + +Enfin, une recherche générique sur Google ou sur Internet "R \" vous enverra souvent +soit à la documentation du package appropriée, soit à un forum utile où quelqu'un +d'autre a déjà posé votre question. + +### Je suis coincé... Je reçois un message d'erreur que je ne comprends pas + +Commencez par rechercher le message d'erreur sur Google. Cependant, cela ne fonctionne pas toujours très bien +car souvent, les développeurs de packages s'appuient sur la détection d'erreurs fournie par R. Vous +vous retrouvez avec des messages d'erreur généraux qui pourraient ne pas être très utiles pour diagnostiquer un problème. +problème (par exemple "indice hors limites"). Si le message est très générique, vous +pouvez également inclure le nom de la fonction ou du package que vous utilisez dans votre +requête. + +Cependant, vous devriez vérifier Stack Overflow. Recherchez en utilisant la balise `[r]`. La plupart des +questions ont déjà reçu une réponse, mais le défi consiste à utiliser les bons +mots dans la recherche pour trouver les +réponses : + +[http://stackoverflow.com/questions/tagged/r](https://stackoverflow.com/questions/tagged/r) + +The [Introduction to R](https://cran.r-project.org/doc/manuals/R-intro.pdf) can +also be dense for people with little programming experience but it is a good +place to understand the underpinnings of the R language. + +La [FAQ R](https://cran.r-project.org/doc/FAQ/R-FAQ.html) est dense et technique +mais elle regorge d'informations utiles. + +### Demander de l'aide + +La clé pour recevoir de l’aide de quelqu’un est qu’il comprenne rapidement +votre problème. Vous devez faire en sorte qu'il soit aussi simple que possible d'identifier où +pourrait se situer le problème. + +Essayez d'utiliser les mots corrects pour décrire votre problème. Par exemple, un package +n’est pas la même chose qu’une bibliothèque. La plupart des gens +comprendront ce que vous vouliez dire, mais d'autres ont des sentiments très forts +à propos de la différence de sens. Le point clé est que cela peut rendre +les choses déroutantes pour les personnes qui essaient de vous aider. Soyez aussi précis que +possible lorsque vous décrivez votre problème. + +Si possible, essayez de réduire ce qui ne fonctionne pas à un simple \*exemple reproductible +\*. Si vous pouvez reproduire le problème en utilisant un très petit cadre de données +au lieu de celui de 50 000 lignes et 10 000 colonnes, fournissez le petit +avec la description de votre problème. Le cas échéant, essayez +de généraliser ce que vous faites afin que même les personnes qui ne font pas partie de votre domaine +puissent comprendre la question. Par exemple, au lieu d'utiliser un sous-ensemble +de votre ensemble de données réel, créez un petit (3 colonnes, 5 lignes) +générique. Pour plus d'informations sur la façon d'écrire un exemple +reproductible, voir cet article de Hadley +Wickham. + +Pour partager un objet avec quelqu'un d'autre, s'il est relativement petit, vous +pouvez utiliser la fonction `dput()`. Il produira du code R qui peut être utilisé +pour recréer exactement le même objet que celui en mémoire : + +```{r, results="show", purl=TRUE} +## iris is an example data frame that comes with R and head() is a +## function that returns the first part of the data frame +dput(head(iris)) +``` + +If the object is larger, provide either the raw file (i.e., your CSV +file) with your script up to the point of the error (and after +removing everything that is not relevant to your +issue). Alternativement, en particulier si votre question n'est pas liée +à un bloc de données, vous pouvez enregistrer n'importe quel objet R dans un fichier[^export] : + +```{r, eval=FALSE, purl=FALSE} +saveRDS(iris, file="/tmp/iris.rds") +``` + +Le contenu de ce fichier n'est cependant pas lisible par l'homme et ne peut pas être +publié directement sur Stack Overflow. Au lieu de cela, il peut être envoyé à quelqu'un +par email qui pourra le lire avec la commande `readRDS()` (ici, +suppose que le fichier téléchargé se trouve dans un dossier `Téléchargements` dans le +répertoire personnel de l'utilisateur) : + +```{r, eval=FALSE, purl=FALSE} +some_data <- readRDS(file="~/Downloads/iris.rds") +``` + +Dernier point, mais non le moindre, **incluez toujours la sortie de `sessionInfo()`** +car elle fournit des informations critiques sur votre plate-forme, les versions de R et +les packages que vous utilisez. utilisation, et d'autres informations qui peuvent être très utiles +pour comprendre votre problème. + +```{r, results="show", purl=TRUE} +sessionInfo() +``` + +### Où demander de l'aide ? + +- La personne assise à côté de vous pendant le cours. N'hésitez pas à + parler à votre voisin pendant l'atelier, comparer vos réponses, + et demander de l'aide. +- Vos collègues amicaux : si vous connaissez quelqu'un avec plus d'expérience + que vous, il pourra et voudra peut-être vous aider. +- [Stack Overflow](https://stackoverflow.com/questions/tagged/r) : si + votre question n'a pas reçu de réponse auparavant et est bien conçue, + il y a de fortes chances que vous obteniez un réponse en moins de 5 minutes. N'oubliez pas de + suivre leurs directives sur comment poser une bonne + question. +- La liste de diffusion R-help + : elle est lue par un + grand nombre de personnes (dont la plupart des l'équipe principale de R), beaucoup de gens + y publient des messages, mais le ton peut être assez sec, et il n'est pas toujours + très accueillant pour les nouveaux utilisateurs. Si votre question est valide, vous avez + de chances d'obtenir une réponse très rapidement, mais ne vous attendez pas à ce qu'elle vienne + avec des visages souriants. Aussi, ici plus qu'ailleurs, veillez à + d'utiliser un vocabulaire correct (sinon vous pourriez obtenir une réponse pointant + vers une mauvaise utilisation de vos mots plutôt que de répondre à votre + question). Vous aurez également plus de succès si votre question concerne + une fonction de base plutôt qu'un package spécifique. +- Si votre question concerne un package spécifique, vérifiez s'il existe une liste de diffusion + pour celui-ci. Habituellement, il est inclus dans le fichier DESCRIPTION + du package accessible en utilisant + `packageDescription("name-of-package")`. Vous pouvez également essayer d'envoyer + un e-mail directement à l'auteur du package ou d'ouvrir un ticket sur le référentiel de code + (par exemple, GitHub). +- Il existe également quelques listes de diffusion thématiques (SIG, + phylogénétique, etc...), la liste complète est + [ici](https://www.r-project.org/ mail.html). + +### Davantage de ressources + +- Le [Guide de publication](https://www.r-project.org/posting-guide.html) pour + les listes de diffusion R. + +- Comment demander de l'aide R + + directives utiles. + +- Ce billet de blog de Jon + Skeet + contient des conseils assez complets sur la façon dont pour poser des questions de programmation. + +- Le package [reprex](https://cran.rstudio.com/web/packages/reprex/) + est très utile pour créer des exemples reproductibles lorsque vous demandez de l'aide à + . The rOpenSci community call "How to ask questions so they get + answered" (Github + link and video + recording) includes a presentation of + the reprex package and of its philosophy. + +## Forfaits R + +### Chargement des paquets + +Comme nous l'avons vu plus haut, les packages R jouent un rôle fondamental dans R. Les +utilisent les fonctionnalités d'un package, en supposant qu'il soit installé, il faut +d'abord le charger pour pouvoir l'utiliser . Cela se fait avec la fonction +`library()`. Ci-dessous, nous chargeons `ggplot2`. + +```{r loadp, eval=FALSE, purl=TRUE} +library("ggplot2") +``` + +### Installation des packages + +Le référentiel de packages par défaut est The _Comprehensive R Archive +Network_ (CRAN), et tout package disponible sur CRAN peut être +installé avec la fonction `install.packages()`. Ci-dessous, par exemple, +, nous installons le package `dplyr` que nous découvrirons plus tard. + +```{r craninstall, eval=FALSE, purl=TRUE} +install.packages("dplyr") +``` + +Cette commande installera le package `dplyr` ainsi que toutes ses +dépendances, c'est à dire tous les packages sur lesquels il s'appuie pour fonctionner. + +Un autre référentiel majeur de packages R est géré par Bioconductor. [Packages Bioconductor](https://bioconductor.org/packages/release/BiocViews.html#___Software) sont gérés et installés à l'aide d'un package dédié, +à savoir `BiocManager`, qui peut être installé à partir de CRAN avec + +```{r, eval=FALSE, purl=TRUE} +install.packages("BiocManager") +``` + +Des packages individuels tels que `SummarizedExperiment` (nous l'utiliserons +plus tard), `DESeq2` (pour l'analyse RNA-Seq) et tout autre de Bioconductor ou CRAN peuvent ensuite être +installés avec ` BiocManager :: installer`. + +```{r, eval=FALSE, purl=TRUE} +BiocManager::install("SummarizedExperiment") +BiocManager::install("DESeq2") +``` + +Par défaut, `BiocManager::install()` vérifiera également tous vos packages installés et verra si des versions plus récentes sont disponibles. S'il y en a, il vous les montrera et vous demandera si vous souhaitez « Mettre à jour tout/certains/aucun ? [a/s/n] :\` et attendez votre réponse. Bien que vous deviez vous efforcer de disposer des versions de packages les plus à jour, en pratique, nous vous recommandons de mettre à jour les packages uniquement lors d'une nouvelle session R avant le chargement des packages. + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Commencez à utiliser R et RStudio + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/fr/episodes/23-starting-with-r.Rmd b/locale/fr/episodes/23-starting-with-r.Rmd new file mode 100644 index 000000000..e352236e0 --- /dev/null +++ b/locale/fr/episodes/23-starting-with-r.Rmd @@ -0,0 +1,924 @@ +--- +source: Rmd +title: Introduction à R +teaching: 60 +exercises: 60 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Définissez les termes suivants relatifs à R : objet, affectation, appel, fonction, arguments, options. +- Attribuez des valeurs aux objets dans R. +- Apprenez à _nommer_ des objets +- Utilisez les commentaires pour informer le script. +- Résoudre des opérations arithmétiques simples dans R. +- Appelez des fonctions et utilisez des arguments pour modifier leurs options par défaut. +- Inspectez le contenu des vecteurs et manipulez leur contenu. +- Sous-ensembler et extraire des valeurs à partir de vecteurs. +- Analysez les vecteurs avec des données manquantes. + +:::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- Premières commandes dans R + +:::::::::::::::::::::::::::::::::::::::::::::::: + +> Cet épisode est basé sur la leçon _Analyse des données et +> Visualisation dans R pour les écologistes_ de Data Carpentries. + +## Créer des objets dans R + +Vous pouvez obtenir le résultat de R simplement en tapant math dans la console : + +```{r, purl=TRUE} +3 + 5 +12 / 7 +``` + +Cependant, pour faire des choses utiles et intéressantes, nous devons attribuer des _valeurs_ à +_objets_. Pour créer un objet, nous devons lui donner un nom suivi de l'opérateur d'affectation +`<-`, et de la valeur que nous voulons lui donner : + +```{r, purl=TRUE} +poids_kg <- 55 +``` + +`<-` est l'opérateur d'affectation. Il attribue des valeurs à droite aux objets +à gauche. Ainsi, après avoir exécuté `x <- 3`, la valeur de `x` est +`3`. La flèche peut être lue comme 3 **entre dans** `x`. Pour des raisons historiques +, vous pouvez également utiliser `=` pour les affectations, mais pas dans tous les contextes +. En raison du +[légères différences](https://blog.revolutionanalytics.com/2008/12/use-equals-or-arrow-for-assignment.html) +dans la syntaxe, il est une bonne pratique de toujours utiliser `<-` pour les affectations. + +In RStudio, typing Alt + \- (push Alt +at the same time as the \- key) will write `<-` in a single +keystroke in a PC, while typing Option + \- (push Option at the same time as the \- key) does the +same in a Mac. + +### Nommer les variables + +Les objets peuvent recevoir n'importe quel nom tel que « x », « current_temperature » ou +« subject_id ». Vous voulez que les noms de vos objets soient explicites et pas trop +longs. Ils ne peuvent pas commencer par un nombre (`2x` n'est pas valide, mais `x2` +l'est). R est sensible à la casse (par exemple, `weight_kg` est différent de +`Weight_kg`). Certains noms ne peuvent pas être utilisés car ils +sont les noms de fonctions fondamentales dans R (par exemple, `if`, `else`, +`for`, voir +[ ici](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Reserved.html) +pour une liste complète). En général, même si c'est autorisé, il est préférable de +de ne pas utiliser d'autres noms de fonctions (par exemple, `c`, `T`, `mean`, `data`, `df`, +` poids`). En cas de doute, consultez l'aide pour voir si le nom est déjà +utilisé. Il est également préférable d'éviter les points (`.`) dans un nom d'objet comme dans +`my.dataset`. There are many functions in R with dots in their names +for historical reasons, but because dots have a special meaning in R +(for methods) and other programming languages, it's best to avoid +them. Il est également recommandé d'utiliser des noms pour les noms d'objets et des verbes +pour les noms de fonctions. Il est important d'être cohérent dans le style de +votre code (où vous placez les espaces, comment vous nommez les objets, etc.). L'utilisation d'un style de codage +cohérent rend votre code plus clair à lire pour votre +futur moi et vos collaborateurs. Dans R, certains guides de style populaires +sont [de Google](https://google.github.io/styleguide/Rguide.xml), le +[tidyverse](https://style. Tidyverse.org/) et le Bioconductor +style +guide. Le +Tidyverse est très complet et peut sembler écrasant au début +. Vous pouvez installer le package +[**`lintr`**](https://github.com/jimhester/lintr) pour +vérifier automatiquement les problèmes dans le style de votre code. + +> **Objets et variables** : ce que l'on appelle des « objets » dans « R » sont +> connus sous le nom de « variables » dans de nombreux autres langages de programmation. Selon +> le contexte, « objet » et « variable » peuvent avoir des significations radicalement +> différentes. Cependant, dans cette leçon, les deux mots sont utilisés +> de manière synonyme. Pour plus d'informations +> [voir ici.](https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Objects) + +Lors de l'attribution d'une valeur à un objet, R n'imprime rien. Vous +pouvez forcer R à imprimer la valeur en utilisant des parenthèses ou en tapant le +nom de l'objet : + +```{r, purl=TRUE} +weight_kg <- 55 # n'imprime rien +(weight_kg <- 55) # mais mettre des parenthèses autour de l'appel imprime la valeur de `weight_kg` +weight_kg # et taper également le nom du objet +``` + +Maintenant que R a « weight_kg » en mémoire, nous pouvons faire de l'arithmétique avec. Pour +exemple, nous pouvons vouloir convertir ce poids en livres (le poids en livres est 2,2 fois le poids en kg) : + +```{r, purl=TRUE} +2.2 * weight_kg +``` + +On peut également changer la valeur d'un objet en lui attribuant une nouvelle : + +```{r, purl=TRUE} +weight_kg <- 57.5 +2.2 * weight_kg +``` + +Cela signifie que l'attribution d'une valeur à un objet ne modifie pas les valeurs de +autres objets. Par exemple, stockons le poids de l'animal en livres dans un nouvel objet +, `weight_lb` : + +```{r, purl=TRUE} +weight_lb <- 2.2 * weight_kg +``` + +puis remplacez « weight_kg » par 100. + +```{r} +weight_kg <- 100 +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi: + +Selon vous, quel est le contenu actuel de l'objet `weight_lb` ? +126\.5 ou 220 ? + +:::::::::::::::::::::::::::::::::::::::::::::::: + +## commentaires + +Le caractère de commentaire dans R est `#`, tout ce qui se trouve à droite d'un `#` dans un script +sera ignoré par R. Il est utile de laisser des notes et +des explications dans vos scripts . + +RStudio permet de commenter ou décommenter facilement un paragraphe : après +sélectionnant les lignes que vous souhaitez commenter, appuyez en même temps sur +votre clavier Ctrl + Maj + C. If +you only want to comment out one line, you can put the cursor at any +location of that line (i.e. no need to select the whole line), then +press Ctrl + Shift + C. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi + +Quelles sont les valeurs après chaque instruction suivante ? + +```{r, purl=TRUE} +mass <- 47.5 # mass? +age <- 122 # age? +mass <- mass * 2.0 # mass? +age <- age - 20 # age? +mass_index <- mass/age # mass_index? +``` + +:::::::::::::::::::::::::::::::::::::::::::::::: + +## Fonctions et leurs arguments + +Les fonctions sont des "scripts prédéfinis" qui automatisent des ensembles de commandes plus complexes +, y compris les affectations d'opérations, etc. De nombreuses fonctions sont prédéfinies ou peuvent être +rendues disponibles en important des _packages_ R (nous en parlerons plus tard). Une fonction +obtient généralement une ou plusieurs entrées appelées _arguments_. Les fonctions renvoient souvent (mais pas +toujours) une _valeur_. Un exemple typique serait la fonction `sqrt()`. L'entrée +(l'argument) doit être un nombre et la valeur de retour (en fait, la sortie +) est la racine carrée de ce nombre. Exécuter une fonction (« l'exécuter ») +est appelé _appeler_ la fonction. Un exemple d'appel de fonction est : + +```{r, eval=FALSE, purl=FALSE} +b <- sqrt(a) +``` + +Ici, la valeur de `a` est donnée à la fonction `sqrt()`, la fonction `sqrt()` +calcule la racine carrée, et renvoie la valeur qui est ensuite attribuée à +l'objet 'b'. Cette fonction est très simple car elle ne prend qu’un seul argument. + +The return 'value' of a function need not be numerical (like that of `sqrt()`), +and it also does not need to be a single item: it can be a set of things, or +even a dataset. Nous le verrons lorsque nous lirons des fichiers de données dans R. + +Les arguments peuvent être n'importe quoi, non seulement des nombres ou des noms de fichiers, mais aussi d'autres objets +. La signification exacte de chaque argument diffère selon la fonction et doit être +recherchée dans la documentation (voir ci-dessous). Certaines fonctions prennent des arguments qui +peuvent soit être spécifiés par l'utilisateur, soit, s'ils sont laissés de côté, prendre une valeur _par défaut_ : +ceux-ci sont appelés _options_. Les options sont généralement utilisées pour modifier le fonctionnement de la fonction +, par exemple si elle ignore les « mauvaises valeurs » ou quel symbole +utiliser dans un tracé. Cependant, si vous souhaitez quelque chose de spécifique, vous pouvez spécifier une valeur +de votre choix qui sera utilisée à la place de la valeur par défaut. + +Essayons une fonction qui peut prendre plusieurs arguments : `round()`. + +```{r, results="show", purl=TRUE} +round(3.14159) +``` + +Ici, nous avons appelé `round()` avec un seul argument, `3.14159`, et il a +renvoyé la valeur `3`. En effet, la valeur par défaut est d'arrondir au nombre entier +le plus proche. Si nous voulons plus de chiffres, nous pouvons voir comment procéder en obtenant +des informations sur la fonction `round`. Nous pouvons utiliser `args(round)` ou consulter l'aide +pour cette fonction en utilisant `?round`. + +```{r, results="show", purl=TRUE} +args(round) +``` + +```{r, eval=FALSE, purl=TRUE} +?round +``` + +Nous voyons que si nous voulons un nombre différent de chiffres, nous pouvons +taper `digits=2` ou autant que nous le voulons. + +```{r, results="show", purl=TRUE} +round(3.14159, digits = 2) +``` + +Si vous fournissez les arguments exactement dans le même ordre que celui dans lequel ils sont définis, vous +n'avez pas besoin de les nommer : + +```{r, results="show", purl=TRUE} +round(3.14159, 2) +``` + +Et si vous nommez les arguments, vous pouvez changer leur ordre : + +```{r, results="show", purl=TRUE} +round(digits = 2, x = 3.14159) +``` + +Il est recommandé de placer les arguments non facultatifs (comme le nombre que vous arrondissez +) en premier dans votre appel de fonction et de spécifier les noms de tous les arguments +facultatifs. Si vous ne le faites pas, quelqu'un qui lit votre code devra peut-être rechercher la définition +d'une fonction avec des arguments inconnus pour comprendre ce que vous faites +. En spécifiant le nom des arguments, vous protégez également +contre d'éventuelles modifications futures dans l'interface de la fonction, qui peuvent +potentiellement ajouter de nouveaux arguments entre ceux existants. + +## Vecteurs et types de données + +Un vecteur est le type de données le plus courant et le plus basique dans R, et est à peu près +le cheval de bataille de R. Un vecteur est composé d'une série de valeurs, telles que +nombres ou caractères. Nous pouvons attribuer une série de valeurs à un vecteur en utilisant +la fonction `c()`. Par exemple, nous pouvons créer un vecteur de poids d'animaux et l'attribuer +à un nouvel objet `weight_g` : + +```{r, purl=TRUE} +weight_g <- c(50, 60, 65, 82) +weight_g +``` + +Un vecteur peut également contenir des caractères : + +```{r, purl=TRUE} +molecules <- c("dna", "rna", "protein") +molecules +``` + +Les guillemets autour de « adn », « arn », etc. sont ici essentiels. Sans les guillemets +, R supposera qu'il existe des objets appelés « adn », « arn » et +« protéine ». Comme ces objets n'existent pas dans la mémoire de R, il y aura +un message d'erreur. + +Il existe de nombreuses fonctions qui vous permettent d'inspecter le contenu d'un vecteur +. `length()` vous indique combien d'éléments se trouvent dans un vecteur particulier : + +```{r, purl=TRUE} +length(weight_g) +length(molecules) +``` + +Une caractéristique importante d'un vecteur est que tous les éléments sont du +même type de données. La fonction `class()` indique la classe (le type d'élément +) d'un objet : + +```{r, purl=TRUE} +class(weight_g) +class(molecules) +``` + +La fonction `str()` fournit un aperçu de la structure d'un objet +et de ses éléments. C'est une fonction utile lorsque vous travaillez avec +des objets volumineux et complexes : + +```{r, purl=TRUE} +str(weight_g) +str(molecules) +``` + +Vous pouvez utiliser la fonction `c()` pour ajouter d'autres éléments à votre vecteur : + +```{r} +weight_g <- c(weight_g, 90) # add to the end of the vector +weight_g <- c(30, weight_g) # add to the beginning of the vector +weight_g +``` + +Dans la première ligne, nous prenons le vecteur d'origine `weight_g`, ajoutons la valeur +`90` à la fin de celui-ci et enregistrons le résultat dans +`weight_g`. Ensuite, nous ajoutons la valeur « 30 » au début, en enregistrant à nouveau +le résultat dans « weight_g ». + +Nous pouvons faire cela encore et encore pour développer un vecteur ou assembler un ensemble de données +. Au fur et à mesure que nous programmons, cela peut être utile pour ajouter les résultats que nous +collectons ou calculons. + +Un **vecteur atomique** est le **type de données** R le plus simple et est un vecteur linéaire +d'un seul type. Ci-dessus, nous avons vu 2 des 6 principaux types de vecteurs \*\*atomiques +\*\* que R utilise : `"caractère"` et `"numérique"` (ou +`"double"`). Ce sont les éléments de base à partir desquels tous les objets R +sont construits. Les 4 autres types de **vecteurs atomiques** sont : + +- `"logique"` pour `TRUE` et `FALSE` (le type de données booléen) +- `"integer"` pour les nombres entiers (par exemple, `2L`, le `L` indique à R + que c'est un entier) +- `"complexe"` pour représenter des nombres complexes avec des parties réelles et imaginaires + (par exemple, `1 + 4i`) et c'est tout ce que nous allons dire à leur sujet +- `"raw"` pour les bitstreams dont nous ne parlerons pas davantage + +Vous pouvez vérifier le type de votre vecteur en utilisant la fonction `typeof()` +et en saisissant votre vecteur comme argument. + +Les vecteurs sont l'une des nombreuses **structures de données** utilisées par R. Les autres +importants sont les listes (`list`), les matrices (`matrix`), les trames de données +(`data.frame`), les facteurs (`factor`) et les tableaux (`array` ). + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi: + +Nous avons vu que les vecteurs atomiques peuvent être de type caractère, numérique (ou +double), entier et logique. Mais que se passe-t-il si nous essayons de mélanger +ces types dans un seul vecteur ? + +::::::::::::::: solution + +## Solution + +R les convertit implicitement pour qu'ils soient tous du même type + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi: + +Que se passera-t-il dans chacun de ces exemples ? (indice : utilisez `class()` pour +vérifier le type de données de vos objets et tapez leurs noms pour voir ce qui se passe) : + +```{r, eval=TRUE} +num_char <- c(1, 2, 3, "a") +num_logical <- c(1, 2, 3, TRUE, FALSE) +char_logical <- c("a", "b", "c", TRUE) +tricky <- c(1, 2, 3, "4") +``` + +::::::::::::::: solution + +## Solution + +```{r, purl=TRUE} +class(num_char) +num_char +class(num_logical) +num_logical +class(char_logical) +char_logical +class(tricky) +tricky +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi: + +Pourquoi pensez-vous que cela arrive ? + +::::::::::::::: solution + +## Solution + +Les vecteurs ne peuvent appartenir qu’à un seul type de données. R essaie de convertir (contraindre) +le contenu de ce vecteur pour trouver un _dénominateur commun_ qui +ne perd aucune information. + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi: + +Combien de valeurs dans `combined_logical` sont `"TRUE"` (sous forme de caractère) +dans l'exemple suivant : + +```{r, eval=TRUE} +num_logical <- c(1, 2, 3, TRUE) +char_logical <- c("a", "b", "c", TRUE) +combined_logical <- c(num_logical, char_logical) +``` + +::::::::::::::: solution + +## Solution + +Seulement un. Il n'y a pas de mémoire des types de données passés et la coercition +se produit la première fois que le vecteur est évalué. Par conséquent, le `TRUE` +dans `num_logical` est converti en `1` avant d'être converti +en `"1"` dans `combined_logical`. + +```{r} +combined_logical +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi: + +Dans R, nous appelons la conversion d'objets d'une classe vers une autre classe +_coercition_. Ces conversions se produisent selon une hiérarchie, +selon laquelle certains types sont préférentiellement contraints vers d'autres types. Pouvez-vous +dessiner un diagramme qui représente la hiérarchie de la façon dont ces types de données +sont forcés ? + +::::::::::::::: solution + +## Solution + +logique → numérique → caractère ← logique + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +```{r, echo=FALSE, eval=FALSE, purl=TRUE} +## We've seen that atomic vectors can be of type character, numeric, integer, and +## logical. But what happens if we try to mix these types in a single +## vector? + +## What will happen in each of these examples? (hint: use `class()` to +## check the data type of your object) +num_char <- c(1, 2, 3, "a") + +num_logical <- c(1, 2, 3, TRUE) + +char_logical <- c("a", "b", "c", TRUE) + +tricky <- c(1, 2, 3, "4") + +## Why do you think it happens? + +## You've probably noticed that objects of different types get +## converted into a single, shared type within a vector. In R, we call +## converting objects from one class into another class +## _coercion_. These conversions happen according to a hierarchy, +## whereby some types get preferentially coerced into other types. Can +## you draw a diagram that represents the hierarchy of how these data +## types are coerced? +``` + +## Vecteurs de sous-ensemble + +Si l'on veut extraire une ou plusieurs valeurs d'un vecteur, il faut +fournir un ou plusieurs indices entre crochets. Par exemple: + +```{r, results="show", purl=TRUE} +molecules <- c("dna", "rna", "peptide", "protein") +molecules[2] +molecules[c(3, 2)] +``` + +On peut également répéter les indices pour créer un objet avec plus d'éléments +que celui d'origine : + +```{r, results="show", purl=TRUE} +more_molecules <- molecules[c(1, 2, 3, 2, 1, 4)] +more_molecules +``` + +Les indices R commencent à 1. Les langages de programmation comme Fortran, MATLAB, +Julia et R commencent à compter à 1, car c'est ce que font généralement les êtres humains +. Les langages de la famille C (y compris C++, Java, Perl, +et Python) comptent à partir de 0 car c'est plus simple à faire pour les ordinateurs. + +Enfin, il est également possible d'obtenir tous les éléments d'un vecteur +sauf certains éléments spécifiés en utilisant des indices négatifs : + +```{r} +molecules ## all molecules +molecules[-1] ## all but the first one +molecules[-c(1, 3)] ## all but 1st/3rd ones +molecules[c(-1, -3)] ## all but 1st/3rd ones +``` + +## Sous-ensemble conditionnel + +Une autre méthode courante de sous-ensemble consiste à utiliser un vecteur logique. `TRUE` +sélectionnera l'élément avec le même index, tandis que `FALSE` ne le fera pas : + +```{r, purl=TRUE} +weight_g <- c(21, 34, 39, 54, 55) +weight_g[c(TRUE, FALSE, TRUE, TRUE, FALSE)] +``` + +Généralement, ces vecteurs logiques ne sont pas tapés à la main, mais sont la sortie +d'autres fonctions ou tests logiques. Par exemple, si vous +souhaitez sélectionner uniquement les valeurs supérieures à 50 : + +```{r, purl=TRUE} +## will return logicals with TRUE for the indices that meet +## the condition +weight_g > 50 +## so we can use this to select only the values above 50 +weight_g[weight_g > 50] +``` + +Vous pouvez combiner plusieurs tests en utilisant `&` (les deux conditions sont vraies, +AND) ou `|` (au moins une des conditions est vraie, OR) : + +```{r, results="show", purl=TRUE} +weight_g[weight_g < 30 | weight_g > 50] +weight_g[weight_g >= 30 & weight_g == 21] +``` + +Ici, `<` signifie "inférieur à", `>` pour "supérieur à", `>=` pour +"supérieur ou égal à" et `==` pour "égal à". The double equal +sign `==` is a test for numerical equality between the left and right +hand sides, and should not be confused with the single `=` sign, which +performs variable assignment (similar to `<-`). + +Une tâche courante consiste à rechercher certaines chaînes dans un vecteur. On pourrait +utiliser l'opérateur "ou" `|` pour tester l'égalité de plusieurs valeurs, mais +cela peut rapidement devenir fastidieux. La fonction `%in%` permet de +tester si l'un des éléments d'un vecteur de recherche est trouvé : + +```{r, purl=TRUE} +molecules <- c("dna", "rna", "protein", "peptide") +molecules[molecules == "rna" | molecules == "dna"] # returns both rna and dna +molecules %in% c("rna", "dna", "metabolite", "peptide", "glycerol") +molecules[molecules %in% c("rna", "dna", "metabolite", "peptide", "glycerol")] +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi: + +Pouvez-vous comprendre pourquoi « quatre » > « cinq » renvoie « VRAI » ? + +::::::::::::::: solution + +## Solution + +```{r} +"four" > "five" +``` + +Lorsque vous utilisez `>` ou `<` sur des chaînes, R compare leur ordre alphabétique. +Ici, `"quatre"` vient après `"cinq"`, et est donc _supérieur à_ +. + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Des noms + +Il est possible de nommer chaque élément d'un vecteur. Le morceau de code ci-dessous +montre un vecteur initial sans aucun nom, comment les noms sont définis et +récupérés. + +```{r} +x <- c(1, 5, 3, 5, 10) +names(x) ## no names +names(x) <- c("A", "B", "C", "D", "E") +names(x) ## now we have names +``` + +Lorsqu'un vecteur possède des noms, il est possible d'accéder aux éléments par leur nom +, en plus de leur index. + +```{r} +x[c(1, 3)] +x[c("A", "C")] +``` + +## Données manquantes + +Comme R a été conçu pour analyser des ensembles de données, il inclut le concept de +données manquantes (ce qui est rare dans d'autres langages de programmation +). Les données manquantes sont représentées dans les vecteurs par « NA ». + +Lorsque vous effectuez des opérations sur des nombres, la plupart des fonctions renverront « NA » si +les données avec lesquelles vous travaillez incluent des valeurs manquantes. Cette fonctionnalité +rend plus difficile l'ignorance des cas où vous avez affaire à +données manquantes. Vous pouvez ajouter l'argument `na.rm = TRUE` pour calculer +le résultat en ignorant les valeurs manquantes. + +```{r} +heights <- c(2, 4, 4, NA, 6) +mean(heights) +max(heights) +mean(heights, na.rm = TRUE) +max(heights, na.rm = TRUE) +``` + +Si vos données incluent des valeurs manquantes, vous souhaiterez peut-être vous familiariser +avec les fonctions `is.na()`, `na.omit()` et `complete.cases()`. Voir +ci-dessous pour des exemples. + +```{r} +## Extract those elements which are not missing values. +heights[!is.na(heights)] + +## Returns the object with incomplete cases removed. +## The returned object is an atomic vector of type `"numeric"` +## (or `"double"`). +na.omit(heights) + +## Extract those elements which are complete cases. +## The returned object is an atomic vector of type `"numeric"` +## (or `"double"`). +heights[complete.cases(heights)] +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi: + +1. En utilisant ce vecteur de hauteurs en pouces, créez un nouveau vecteur en supprimant les NA. + +```{r} +heights <- c(63, 69, 60, 65, NA, 68, 61, 70, 61, 59, 64, 69, 63, 63, NA, 72, 65, 64, 70, 63, 65) +``` + +2. Utilisez la fonction `median()` pour calculer la médiane du vecteur `heights`. +3. Utilisez R pour déterminer combien de personnes dans l’ensemble mesurent plus de 67 pouces. + +::::::::::::::: solution + +## Solution + +```{r, purl=TRUE} +heights_no_na <- heights[!is.na(heights)] +## or +heights_no_na <- na.omit(heights) +``` + +```{r, purl=TRUE} +median(heights, na.rm = TRUE) +``` + +```{r, purl=TRUE} +heights_above_67 <- heights_no_na[heights_no_na > 67] +length(heights_above_67) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Génération de vecteurs {#sec:genvec} + +```{r, echo=FALSE} +set.seed(1) +``` + +### Constructeurs + +Il existe quelques fonctions pour générer des vecteurs de différents types. Pour +générer un vecteur de valeurs numériques, on peut utiliser le constructeur `numeric()` +, fournissant la longueur du vecteur de sortie comme paramètre +. Les valeurs seront initialisées à 0. + +```{r, purl=TRUE} +numeric(3) +numeric(10) +``` + +Notez que si l'on demande un vecteur de numériques de longueur 0, on obtient +exactement cela : + +```{r, purl=TRUE} +numeric(0) +``` + +Il existe des constructeurs similaires pour les caractères et les logiques, nommés respectivement +`character()` et `logical()`. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi: + +Quelles sont les valeurs par défaut pour les caractères et les vecteurs logiques ? + +::::::::::::::: solution + +## Solution + +```{r, purl=TRUE} +character(2) ## the empty character +logical(2) ## FALSE +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +### Répliquer des éléments + +La fonction `rep` permet de répéter une valeur un certain nombre de +fois. Si nous voulons initier un vecteur de numériques de longueur 5 avec +la valeur -1, par exemple, nous pourrions faire ce qui suit : + +```{r, purl=TRUE} +rep(-1, 5) +``` + +De même, pour générer un vecteur rempli de valeurs manquantes, ce qui +est souvent une bonne façon de commencer, sans poser d'hypothèses sur les données +à collecter : + +```{r, purl=TRUE} +rep(NA, 5) +``` + +`rep` peut prendre en entrée des vecteurs de n'importe quelle longueur (ci-dessus, nous avons utilisé des vecteurs +de longueur 1) et de n'importe quel type. Par exemple, si nous voulons répéter cinq fois les valeurs +1, 2 et 3, nous procéderions comme suit : + +```{r, purl=TRUE} +rep(c(1, 2, 3), 5) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi: + +Et si nous voulions répéter les valeurs 1, 2 et 3 cinq fois, mais que +obtenait cinq 1, cinq 2 et cinq 3 dans cet ordre ? Il existe deux +possibilités - voir `?rep` ou `?sort` pour obtenir de l'aide. + +::::::::::::::: solution + +## Solution + +```{r, purl=TRUE} +rep(c(1, 2, 3), each = 5) +sort(rep(c(1, 2, 3), 5)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +### Génération de séquence + +Une autre fonction très utile est `seq`, pour générer une séquence de +nombres. Par exemple, pour générer une séquence d'entiers de 1 à 20 +par pas de 2, on utiliserait : + +```{r, purl=TRUE} +seq(from = 1, to = 20, by = 2) +``` + +La valeur par défaut de `by` est 1 et, étant donné que la génération d'une séquence +d'une valeur à une autre avec des pas de 1 est fréquemment utilisée, +il existe un raccourci : + +```{r, purl=TRUE} +seq(1, 5, 1) +seq(1, 5) ## default by +1:5 +``` + +Pour générer une séquence de nombres de 1 à 20 de longueur finale de 3, +on utiliserait : + +```{r, purl=TRUE} +seq(from = 1, to = 20, length.out = 3) +``` + +### Échantillons aléatoires et permutations + +Un dernier groupe de fonctions utiles sont celles qui génèrent des données aléatoires +. Le premier, `sample`, génère une permutation aléatoire de +un autre vecteur. Par exemple, pour tirer au sort un ordre aléatoire de 10 étudiants +à l'examen oral, j'attribue d'abord à chaque étudiant un numéro de 1 à dix (par exemple +en fonction de l'ordre alphabétique de son nom) puis : + +```{r, purl=TRUE} +sample(1:10) +``` + +Sans autres arguments, `sample` renverra une permutation de tous les +éléments du vecteur. Si je veux un échantillon aléatoire d'une certaine taille, je +définirais cette valeur comme deuxième argument. Ci-dessous, j'échantillonne 5 +lettres aléatoires de l'alphabet contenu dans le vecteur `letters` prédéfini : + +```{r, purl=TRUE} +sample(letters, 5) +``` + +Si je voulais une sortie plus grande que le vecteur d'entrée, ou pouvoir +dessiner certains éléments plusieurs fois, je devrais définir l'argument `replace` +sur `TRUE` : + +```{r, purl=TRUE} +sample(1:5, 10, replace = TRUE) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi: + +En essayant les fonctions ci-dessus, vous aurez réalisé que les échantillons +sont effectivement aléatoires et qu'on n'obtient pas deux fois la même permutation +. Pour pouvoir reproduire ces tirages aléatoires, on peut +définir manuellement la graine de génération de nombres aléatoires avec `set.seed()` +avant de tirer l'échantillon aléatoire. + +Testez cette fonctionnalité avec votre voisin. Dessinez d'abord deux permutations aléatoires +de « 1:10 » indépendamment et observez que vous obtenez +résultats différents. + +Définissez maintenant la graine avec, par exemple, `set.seed(123)` et répétez le tirage au sort +. Observez que vous obtenez désormais les mêmes tirages au sort. + +Répétez en définissant une graine différente. + +::::::::::::::: solution + +## Solution + +Différentes permutations + +```{r, purl=TRUE} +sample(1:10) +sample(1:10) +``` + +Mêmes permutations avec la graine 123 + +```{r, purl=TRUE} +set.seed(123) +sample(1:10) +set.seed(123) +sample(1:10) +``` + +Une graine différente + +```{r, purl=TRUE} +set.seed(1) +sample(1:10) +set.seed(1) +sample(1:10) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +### Extraire des échantillons à partir d'une distribution normale + +La dernière fonction que nous allons voir est `rnorm`, qui tire un échantillon aléatoire +à partir d'une distribution normale. Deux distributions normales de moyennes 0 +et 100 et d'écarts types 1 et 5, notées _N(0, 1)_ et +_N(100, 5)_, sont présentées ci-dessous. + +```{r, echo=FALSE, fig.width=12, fig.height=6, fig.cap="Two normal distributions: *N(0, 1)* on the left and *N(100, 5)* on the right."} +par(mfrow = c(1, 2)) +plot(density(rnorm(1000)), main = "", sub = "N(0, 1)") +plot(density(rnorm(1000, 100, 5)), main = "", sub = "N(100, 5)") +``` + +Les trois arguments, `n`, `mean` et `sd`, définissent la taille de l'échantillon +, et les paramètres de la distribution normale, c'est-à-dire la moyenne +et son écart type. Les valeurs par défaut de ce dernier sont 0 et 1. + +```{r, purl=TRUE} +rnorm(5) +rnorm(5, 2, 2) +rnorm(5, 100, 5) +``` + +Maintenant que nous avons appris à écrire des scripts et les bases des structures de données +de R, nous sommes prêts à commencer à travailler avec des données plus volumineuses et à +en apprendre davantage sur les trames de données. + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Comment interagir avec R + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/fr/episodes/25-starting-with-data.Rmd b/locale/fr/episodes/25-starting-with-data.Rmd new file mode 100644 index 000000000..2fd7e9425 --- /dev/null +++ b/locale/fr/episodes/25-starting-with-data.Rmd @@ -0,0 +1,784 @@ +--- +source: Rmd +title: Commencer par les données +teaching: 30 +exercises: 30 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Décrivez ce qu'est un « data.frame ». +- Chargez des données externes à partir d'un fichier .csv dans un bloc de données. +- Résumer le contenu d'un bloc de données. +- Décrivez ce qu'est un facteur. +- Convertissez entre les chaînes et les facteurs. +- Réorganisez et renommez les facteurs. +- Formater les dates. +- Exportez et enregistrez les données. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- Première analyse de données dans R + +:::::::::::::::::::::::::::::::::::::::::::::::: + +> Cet épisode est basé sur la leçon _Analyse des données et +> Visualisation dans R pour les écologistes_ de Data Carpentries. + +## Présentation des données d'expression des gènes + +Nous allons utiliser une partie des données publiées par Blackmore , _L'effet +de l'infection des voies respiratoires supérieures sur les modifications transcriptomiques du +SNC_. Le but de l'étude était de déterminer l'effet d'une infection des voies respiratoires supérieures +sur les modifications de la transcription de l'ARN se produisant +dans le cervelet et la moelle épinière après l'infection. Gender matched eight +week old C57BL/6 mice were inoculated with saline or with Influenza A by +intranasal route and transcriptomic changes in the cerebellum and +spinal cord tissues were evaluated by RNA-seq at days 0 +(non-infected), 4 and 8. + +L'ensemble de données est stocké sous forme de fichier CSV (valeurs séparées par des virgules). Chaque ligne +contient des informations pour une seule mesure d'expression d'ARN, et les onze premières colonnes +représentent : + +| Colonne | Description | +| ----------- | ------------------------------------------------------------------------------------------------------------------------ | +| gène | Le nom du gène qui a été mesuré | +| échantillon | Le nom de l’échantillon dans lequel l’expression du gène a été mesurée | +| expression | La valeur de l'expression des gènes | +| organisme | L'organisme/l'espèce - ici toutes les données proviennent de souris | +| âge | L'âge de la souris (toutes les souris avaient 8 semaines ici) | +| sexe | Le sexe de la souris | +| infection | L'état d'infection de la souris, c'est-à-dire infectée par la grippe A ou non infectée. | +| souche | La souche grippale A. | +| temps | La durée de l'infection (en jours). | +| tissu | Le tissu utilisé pour l'expérience d'expression génique, c'est-à-dire le cervelet ou la moelle épinière. | +| souris | L'identifiant unique de la souris. | + +Nous allons utiliser la fonction R `download.file()` pour télécharger le fichier CSV +qui contient les données d'expression génique, et nous utiliserons +`read.csv()` pour charger en mémoire le contenu du fichier CSV en tant qu'objet +de classe `data.frame`. Dans la commande `download.file`, la première entrée +est une chaîne de caractères avec l'URL source. Cette URL source +télécharge un fichier CSV à partir d'un référentiel GitHub. Le texte après la virgule +("data/rnaseq.csv"`) est la destination du fichier sur votre machine locale +. Vous aurez besoin d'un dossier sur votre ordinateur appelé +`"data"`dans lequel vous téléchargerez le fichier. Cette commande télécharge donc le fichier distant +, le nomme`"rnaseq.csv"`et l'ajoute à un dossier +préexistant nommé`"data"\`. + +```{r, eval=TRUE} +download.file(url = "https://github.com/carpentries-incubator/bioc-intro/raw/main/episodes/data/rnaseq.csv", + destfile = "data/rnaseq.csv" ) +``` + +Vous êtes maintenant prêt à charger les données : + +```{r, eval=TRUE, purl=TRUE} +arn <- read.csv("data/rnaseq.csv") +``` + +Cette instruction ne produit aucune sortie car, comme vous vous en souvenez peut-être +, les affectations n'affichent rien. Si nous voulons vérifier que +nos données ont été chargées, nous pouvons voir le contenu du bloc de données en +en tapant son nom : + +```{r, eval=FALSE} +arn +``` + +Ouah... c'était beaucoup de production. Au moins, cela signifie que les données ont été chargées +correctement. Vérifions le haut (les 6 premières lignes) de ce bloc de données +en utilisant la fonction `head()` : + +```{r, purl=TRUE} +head(rna) +## Essayez aussi +## View(rna) +``` + +**Note** + +`read.csv()` suppose que les champs sont délimités par des virgules, cependant, dans +plusieurs pays, la virgule est utilisée comme séparateur décimal et le +point-virgule (;) est utilisé comme champ délinéateur. Si vous souhaitez lire en +ce type de fichiers dans R, vous pouvez utiliser la fonction `read.csv2()`. Il +se comporte exactement comme `read.csv()` mais utilise des paramètres différents pour +la décimale et les séparateurs de champ. Si vous travaillez avec un autre format +, ils peuvent tous deux être spécifiés par l'utilisateur. Consultez l'aide pour +`read.csv()` en tapant `?read.csv` pour en savoir plus. Il existe également la fonction +`read.delim()` pour lire des fichiers de données séparés par des tabulations. Il est important de +noter que toutes ces fonctions sont en fait des fonctions wrapper pour +la fonction principale `read.table()` avec différents arguments. En tant que tel, +les données ci-dessus auraient également pu être chargées en utilisant `read.table()` +avec l'argument de séparation comme `,`. Le code est comme suit: + +```{r, eval=TRUE, purl=TRUE} +rna <- read.table(file = "data/rnaseq.csv", + sep = ",", + header = TRUE) +``` + +L'argument d'en-tête doit être défini sur TRUE pour pouvoir lire les en-têtes +car par défaut `read.table()` a l'argument d'en-tête défini sur +FALSE. + +## Que sont les trames de données ? + +Les trames de données sont la structure de données _de facto_ pour la plupart des données tabulaires, +et ce que nous utilisons pour les statistiques et le traçage. + +Un bloc de données peut être créé à la main, mais le plus souvent ils sont +générés par les fonctions `read.csv()` ou `read.table()` ; en d'autres termes +, lors de l'importation de feuilles de calcul depuis votre disque dur (ou le Web). + +Une trame de données est la représentation de données sous le format d'un tableau +où les colonnes sont des vecteurs qui ont tous la même longueur. Étant donné que les colonnes +sont des vecteurs, chaque colonne doit contenir un seul type de données +(par exemple, des caractères, des entiers, des facteurs). Par exemple, voici une figure +représentant une trame de données comprenant un chiffre, un caractère et un vecteur logique +. + +![](./fig/data-frame.svg) + +Nous pouvons le voir lors de l'inspection de la structure d'une trame de données +avec la fonction `str()` : + +```{r} +str(arn) +``` + +## Inspection des objets `data.frame` + +Nous avons déjà vu comment les fonctions `head()` et `str()` peuvent être utiles pour +vérifier le contenu et la structure d'une trame de données. Voici une +liste non exhaustive de fonctions pour avoir une idée du +contenu/structure des données. Essayons-les ! + +**Taille**: + +- `dim(rna)` - renvoie un vecteur avec le nombre de lignes comme premier élément + et le nombre de colonnes comme deuxième élément (les + **dim**ensions de l'objet ). +- `nrow(rna)` - renvoie le nombre de lignes. +- `ncol(rna)` - renvoie le nombre de colonnes. + +**Contenu**: + +- `head(rna)` - affiche les 6 premières lignes. +- `tail(rna)` - affiche les 6 dernières lignes. + +**Des noms**: + +- `names(rna)` - renvoie les noms de colonnes (synonyme de `colnames()` pour les objets + `data.frame`). +- `rownames(rna)` - renvoie les noms de lignes. + +**Résumé**: + +- `str(rna)` - structure de l'objet et informations sur la classe + , longueur et contenu de chaque colonne. +- `summary(rna)` - statistiques récapitulatives pour chaque colonne. + +Remarque : la plupart de ces fonctions sont "génériques", elles peuvent être utilisées sur d'autres types d'objets +en plus de `data.frame`. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi: + +Sur la base du résultat de `str(rna)`, pouvez-vous répondre aux +questions suivantes ? + +- Quelle est la classe de l’objet « rna » ? +- Combien de lignes et combien de colonnes y a-t-il dans cet objet ? + +::::::::::::::: solution + +## Solution + +- classe : trame de données +- combien de lignes : 66465, combien de colonnes : 11 + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +## Indexation et sous-ensemble de trames de données + +Notre bloc de données « rna » comporte des lignes et des colonnes (il a 2 dimensions) ; si nous +voulons en extraire des données spécifiques, nous devons spécifier les +"coordonnées" que nous voulons. Les numéros de ligne viennent en premier, suivis des numéros de colonne +. Cependant, notez que différentes manières de spécifier ces coordonnées +conduisent à des résultats avec des classes différentes. + +```{r, eval=FALSE, purl=TRUE} +# premier élément de la première colonne du bloc de données (sous forme de vecteur) +rna[1, 1] +# premier élément de la 6ème colonne (sous forme de vecteur) +rna [1, 6] +# première colonne du bloc de données (sous forme de vecteur) +rna[, 1] +# première colonne du bloc de données (sous forme de data.frame ) +rna[1] +# les trois premiers éléments de la 7ème colonne (en tant que vecteur) +rna[1:3, 7] +# la 3ème ligne de la trame de données (en tant que data.frame) +rna[3, ] +# équivalent à head_rna <- head(rna) +head_rna <- rna[1:6, ] +head_rna +``` + +`:` est une fonction spéciale qui crée des vecteurs numériques d'entiers dans +ordre croissant ou décroissant, testez `1:10` et `10:1` pour l'instance +. Voir la section @ref(sec:genvec) pour plus de détails. + +Vous pouvez également exclure certains indices d'un bloc de données à l'aide du signe "`-`" : + +```{r, eval=FALSE, purl=TRUE} +rna[, -1] ## La trame de données entière, sauf la première colonne +rna[-c(7:66465), ] ## Équivalent à head(rna) +``` + +Les trames de données peuvent être sous-ensembles en appelant des indices (comme indiqué précédemment), +mais aussi en appelant directement leurs noms de colonnes : + +```{r, eval=FALSE, purl=TRUE} +rna["gene"] # Result is a data.frame +rna[, "gene"] # Result is a vector +rna[["gene"]] # Result is a vector +rna$gene # Result is a vector +``` + +Dans RStudio, vous pouvez utiliser la fonction de saisie semi-automatique pour obtenir les noms complets et +corrects des colonnes. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi + +1. Créez un `data.frame` (`rna_200`) contenant uniquement les données de + ligne 200 de l'ensemble de données `rna`. + +2. Remarquez comment `nrow()` vous a donné le nombre de lignes dans un `data.frame` ? + +- Utilisez ce numéro pour extraire uniquement la dernière ligne de la trame de données initiale + `rna`. + +- Comparez cela avec ce que vous voyez comme la dernière ligne en utilisant `tail()` pour + assurez-vous qu'il répond aux attentes. + +- Retirez cette dernière ligne en utilisant `nrow()` au lieu du numéro de ligne. + +- Créez un nouveau bloc de données (`rna_last`) à partir de cette dernière ligne. + +3. Utilisez `nrow()` pour extraire la ligne qui se trouve au milieu du dataframe + `rna`. Stockez le contenu de cette ligne dans un objet + nommé `rna_middle`. + +4. Combinez `nrow()` avec la notation `-` ci-dessus pour reproduire le comportement + de `head(rna)`, en ne conservant que la première à la 6ème + lignes de l'ensemble de données rna. + +::::::::::::::: solution + +## Solution + +```{r, purl=TRUE} +## 1. +rna_200 <- rna[200, ] +## 2. +## Sauvegarde de `n_rows` pour améliorer la lisibilité et réduire la duplication +n_rows < - nrow(rna) +rna_last <- rna[n_rows, ] +## 3. +rna_middle <- rna[n_rows / 2, ] +## 4 . +rna_head <- rna[-(7:n_rows), ] +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +## Facteurs + +Les facteurs représentent des **données catégorielles**. Ils sont stockés sous forme d'entiers +associés aux étiquettes et ils peuvent être ordonnés ou non. Alors que les facteurs +ressemblent (et se comportent souvent) à des vecteurs de caractères, ils sont +en fait traités comme des vecteurs entiers par R. Vous devez donc être très +prudent lorsque vous les traitez comme des chaînes. + +Une fois créés, les facteurs ne peuvent contenir qu'un ensemble prédéfini de valeurs, +appelées _niveaux_. Par défaut, R trie toujours les niveaux par ordre alphabétique +. Par exemple, si vous avez un facteur à 2 niveaux : + +```{r, purl=TRUE} +sexe <- factor(c("mâle", "femelle", "femelle", "mâle", "femelle")) +``` + +R will assign `1` to the level `"female"` and `2` to the level +`"male"` (because `f` comes before `m`, even though the first element +in this vector is `"male"`). Vous pouvez le voir en utilisant la fonction +`levels()` et vous pouvez trouver le nombre de niveaux en utilisant `nlevels()` : + +```{r, purl=TRUE} +niveaux(sexe) +nniveaux(sexe) +``` + +Parfois, l'ordre des facteurs n'a pas d'importance, d'autres fois vous +souhaiterez peut-être spécifier l'ordre car il est significatif (par exemple, "faible", +"moyen", "élevé"), il améliore votre visualisation, ou il est requis +par un type particulier d'analyse. Ici, une façon de réorganiser nos niveaux +dans le vecteur « sexe » serait : + +```{r, purl=TRUE} +sex ## commande actuelle +sex <- factor(sex,levels = c("male", "female")) +sex ## après la nouvelle commande +``` + +Dans la mémoire de R, ces facteurs sont représentés par des entiers (1, 2, 3), +mais sont plus informatifs que les entiers car les facteurs sont auto-descriptifs + : `"femelle"`, `"mâle" ` est plus descriptif que `1`, +`2`. Lequel est « mâle » ? Vous ne seriez pas en mesure de le savoir uniquement à partir des données entières +. Les facteurs, en revanche, intègrent cette information. +Ceci est particulièrement utile lorsqu'il existe de nombreux niveaux (comme le biotype du gène +dans notre exemple d'ensemble de données). + +Lorsque vos données sont stockées sous forme de facteur, vous pouvez utiliser la fonction `plot()` +pour avoir un aperçu rapide du nombre d'observations +représenté par chaque niveau de facteur. Regardons le nombre d'hommes +et de femmes dans nos données. + +```{r firstfactorplot, fig.cap="Bar plot of the number of females and males.", purl=TRUE} +intrigue (sexe) +``` + +### Conversion en personnage + +Si vous devez convertir un facteur en vecteur de caractères, vous utilisez +`as.character(x)`. + +```{r, purl=TRUE} +as.personnage (sexe) +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +### Facteurs de renommage + +Si l'on veut renommer ces facteurs, il suffit de changer ses niveaux +: + +```{r, purl=TRUE} +niveaux(sexe) +niveaux(sexe) <- c("M", "F") +sexe +intrigue(sexe) +``` + +:::::::::::::::::::::::::::::::::::::: défi + +## Défi: + +- Renommez « F » et « M » respectivement en « Femme » et « Mâle ». + +::::::::::::::: solution + +## Solution + +```{r, eval=TRUE, purl=TRUE} +niveaux(sexe) +niveaux(sexe) <- c("Homme", "Femme") +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi: + +Nous avons vu comment les trames de données sont créées lors de l'utilisation de `read.csv()`, mais +elles peuvent également être créées à la main avec la fonction `data.frame()`. +Il y a quelques erreurs dans ce « data.frame » fabriqué à la main. Pouvez-vous +les repérer et les réparer ? N'hésitez pas à expérimenter ! + +```{r, eval=FALSE} +animal_data <- data.frame( + animal = c(dog, cat, sea cucumber, sea urchin), + feel = c("furry", "squishy", "spiny"), + weight = c(45, 8 1.1, 0.8)) +``` + +::::::::::::::: solution + +## Solution + +- guillemets manquants autour des noms des animaux +- il manque une entrée dans la colonne "sensation" (probablement pour l'un des animaux à fourrure) +- il manque une virgule dans la colonne poids + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi: + +Pouvez-vous prédire la classe de chacune des colonnes dans l'exemple +suivant ? + +Vérifiez vos suppositions en utilisant `str(country_climate)` : + +- Sont-ils ce à quoi vous vous attendiez ? Pourquoi? Pourquoi pas? + +- Réessayez en ajoutant `stringsAsFactors = TRUE` après la dernière variable + lors de la création du bloc de données. Qu'est ce qu'il se passe maintenant? + `stringsAsFactors` peut également être défini lors de la lecture de feuilles de calcul + basées sur du texte dans R à l'aide de `read.csv()`. + +```{r, eval=FALSE, purl=TRUE} +country_climate <- data.frame( + country = c("Canada", "Panama", "Afrique du Sud", "Australie"), + climat = c("froid", "chaud" , "tempéré", "chaud/tempéré"), + température = c(10, 30, 18, "15"), + hémisphère_nord = c(VRAI, VRAI, FAUX, "FAUX" ), + has_kangaroo = c(FALSE, FALSE, FALSE, 1) +) +``` + +::::::::::::::: solution + +## Solution + +```{r, eval=TRUE, purl=TRUE} +country_climate <- data.frame( + country = c("Canada", "Panama", "Afrique du Sud", "Australie"), + climat = c("froid", "chaud" , "tempéré", "chaud/tempéré"), + température = c(10, 30, 18, "15"), + hémisphère_nord = c(VRAI, VRAI, FAUX, "FAUX" ), + has_kangaroo = c(FALSE, FALSE, FALSE, 1) + ) +str(country_climate) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +La conversion automatique du type de données est parfois une bénédiction, parfois un +désagrément. Sachez qu'il existe, apprenez les règles et vérifiez que les données +que vous importez dans R sont du type correct dans votre bloc de données. Sinon, utilisez-le +à votre avantage pour détecter les erreurs qui auraient pu être introduites lors de la saisie des données +(une lettre dans une colonne qui ne doit contenir que des chiffres par exemple). + +Apprenez-en plus dans ce tutoriel RStudio + + +## Matrices + +Avant de continuer, maintenant que nous avons découvert les trames de données, +récapitulons l'installation du package et découvrons un nouveau type de données, à savoir la +`matrice`. Comme un `data.frame`, une matrice a deux dimensions, des lignes et +colonnes. Mais la différence majeure est que toutes les cellules d'une « matrice » doivent +être du même type : « numérique », « caractère », « logique », ... À cet égard +, les matrices sont plus proches d'un « vecteur » que d'un « data.frame ». + +Le constructeur par défaut d'une matrice est « matrice ». Il faut un vecteur de +valeurs pour remplir la matrice et le nombre de lignes et/ou +colonnes[^ncol]. Les valeurs sont triées le long des colonnes, comme illustré +ci-dessous. + +```{r mat1, purl=TRUE} +m <- matrice (1:9, ncol = 3, nrow = 3) +m +``` + +[^ncol]: Soit le nombre de lignes, soit le nombre de colonnes sont suffisants, l'autre pouvant être déduit de la longueur des valeurs. Essayez ce qui se passe si les valeurs et le nombre de lignes/colonnes ne s'additionnent pas. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi: + +À l'aide de la fonction `installed.packages()`, créez une matrice `caractère` +contenant les informations sur tous les packages actuellement installés sur +votre ordinateur. Explorez-le. + +::::::::::::::: solution + +## Solution: + +```{r pkg_sln, eval=FALSE, purl=TRUE} +## créer la matrice +ip <- Installed.packages() +head(ip) +## essayez aussi View(ip) +## numéro de paquet +nrow(ip) +## noms de tous les packages installés +rownames(ip) +## type d'informations dont nous disposons sur chaque package +noms de colonnes (ip) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +Il est souvent utile de créer de grandes matrices de données aléatoires comme données de test +. L'exercice ci-dessous vous demande de créer une telle matrice avec des données aléatoires +tirées d'une distribution normale de moyenne 0 et d'écart type +1, ce qui peut être fait avec la fonction `rnorm()`. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi: + +Construire une matrice de dimension 1000 par 3 de données normalement distribuées +(moyenne 0, écart type 1) + +::::::::::::::: solution + +## Solution + +```{r rnormmat_sln, purl=TRUE} +set.seed(123) +m <- matrice(rnorm(3000), ncol = 3) +dim(m) +tête(m) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +## Formatage des dates + +L'un des problèmes les plus courants rencontrés par les nouveaux (et expérimentés !) Les utilisateurs de R ont +la conversion des informations de date et d'heure en une variable +appropriée et utilisable lors des analyses. + +### Remarque sur les dates dans les tableurs + +Les dates dans les feuilles de calcul sont généralement stockées dans une seule colonne. Bien que +cela semble la manière la plus naturelle d'enregistrer des dates, ce n'est en réalité pas +la meilleure pratique. Un tableur affichera les dates d'une manière +apparemment correcte (pour un observateur humain), mais la façon dont elle +gère et stocke réellement les dates peut être problématique. Il est souvent +plus sûr de stocker les dates avec ANNÉE, MOIS et JOUR dans des colonnes séparées ou +comme ANNÉE et JOUR DE L'ANNÉE dans des colonnes séparées. + +Tableurs tels que LibreOffice, Microsoft Excel, OpenOffice, +Gnumeric, ... ont des manières différentes (et souvent incompatibles) d'encoder les dates +(même pour le même programme entre les versions et les systèmes d'exploitation +). De plus, Excel peut [transformer des éléments qui ne sont pas des dates en dates +](https://nsaunders.wordpress.com/2012/10/22/gene-name-errors-and-excel-lessons-not -learned/) +(@Zeeberg:2004), par exemple des noms ou des identifiants comme MAR1, DEC1, +OCT4. Donc, si vous évitez globalement le format de date, il est plus facile d' +identifier ces problèmes. + +La section Dates as +data +de la leçon Data Carpentry fournit des informations supplémentaires +sur les pièges des dates avec des feuilles de calcul. + +Nous allons utiliser la fonction `ymd()` du package +**`lubridate`** (qui appartient au **`tidyverse`** ; en savoir plus +[ici] (https://www.tidyverse.org/)). . **`lubridate`** est installé +dans le cadre de l'installation de **`tidyverse`**. Lorsque vous chargez le +**`tidyverse`** (`library(tidyverse)`), les packages de base (les packages +utilisés dans la plupart des analyses de données) sont chargés. **`lubridate`** +n'appartient cependant pas au noyau spiceverse, vous devez donc le charger +explicitement avec `library(lubridate)`. + +Commencez par charger le package requis : + +```{r loadlibridate, message=FALSE, purl=TRUE} +bibliothèque("lubrifier") +``` + +`ymd()` prend un vecteur représentant l'année, le mois et le jour, et le convertit +en un vecteur `Date`. `Date` est une classe de données reconnue par R comme +étant une date et peut être manipulée comme telle. L'argument requis par la fonction +est flexible, mais, à titre de bonne pratique, il s'agit d'un vecteur de caractère +au format "AAAA-MM-JJ". + +Créons un objet date et inspectons la structure : + +```{r, purl=TRUE} +ma_date <- ymd("2015-01-01") +str(ma_date) +``` + +Collons maintenant l'année, le mois et le jour séparément - nous obtenons le même résultat : + +```{r, purl=TRUE} +# sep indique le caractère à utiliser pour séparer chaque composant +my_date <- ymd(paste("2015", "1", "1", sep = "-")) +str(my_date ) +``` + +Familiarisons-nous maintenant avec un pipeline typique de manipulation de date +. Les petites données ci-dessous ont stocké des dates dans différentes colonnes « année », +« mois » et « jour ». + +```{r, purl=TRUE} +x <- data.frame(année = c(1996, 1992, 1987, 1986, 2000, 1990, 2002, 1994, 1997, 1985), + mois = c(2, 3, 3, 10, 1 , 8, 3, 4, 5, 5), + jour = c(24, 8, 1, 5, 8, 17, 13, 10, 11, 24), + valeur = c (4, 5, 1, 9, 3, 8, 10, 2, 6, 7)) +x +``` + +Nous appliquons maintenant cette fonction à l'ensemble de données « x ». Nous créons d'abord un vecteur de caractères +à partir des colonnes `year`, `month` et `day` de `x` +en utilisant `paste()` : + +```{r, purl=TRUE} +coller(x$year, x$month, x$day, sep = "-") +``` + +Ce vecteur de caractères peut être utilisé comme argument pour `ymd()` : + +```{r, purl=TRUE} +ymd(coller(x$year, x$month, x$day, sep = "-")) +``` + +Le vecteur `Date` résultant peut être ajouté à `x` en tant que nouvelle colonne appelée `date` : + +```{r, purl=TRUE} +x$date <- ymd(paste(x$year, x$month, x$day, sep = "-")) +str(x) # remarquez la nouvelle colonne, avec 'date' comme classe +``` + +Assurons-nous que tout a fonctionné correctement. Une façon d'inspecter la nouvelle colonne +est d'utiliser `summary()` : + +```{r, purl=TRUE} +résumé(x$date) +``` + +Notez que `ymd()` s'attend à avoir l'année, le mois et le jour, dans cet ordre +. Si vous avez par exemple le jour, le mois et l'année, vous aurez besoin de +`dmy()`. + +```{r, purl=TRUE} +dmy(coller(x$day, x$month, x$year, sep = "-")) +``` + +`lubdridate` a de nombreuses fonctions pour gérer toutes les variations de date. + +## Résumé des objets R + +Jusqu'à présent, nous avons vu plusieurs types d'objets R variant selon le nombre +de dimensions et s'ils pouvaient stocker un ou plusieurs types de données + : + +- **`vecteur`** : une dimension (ils ont une longueur), un seul type de données. +- **`matrice`** : deux dimensions, un seul type de données. +- **`data.frame`** : deux dimensions, un type par colonne. + +## Listes + +Un type de données que nous n'avons pas encore vu, mais qu'il est utile de connaître, et +découle du résumé que nous venons de voir sont des listes : + +- **`list`** : une dimension, chaque élément peut être d'un type de données différent + . + +Ci-dessous, créons une liste contenant un vecteur de nombres, de caractères, +une matrice, un dataframe et une autre liste : + +```{r list0, purl=TRUE} +l <- list(1:10, ## numérique + lettres, ## caractère + installé.packages(), ## une matrice + voitures, ## un data.frame + liste(1, 2, 3)) ## une liste +longueur(l) +str(l) +``` + +Le sous-ensemble de liste est effectué en utilisant `[]` pour sous-ensembler une nouvelle sous-liste ou `[[]]` +pour extraire un seul élément de cette liste (en utilisant des indices ou des noms, si +la liste est appelé). + +```{r, purl=TRUE} +l[[1]] ## premier élément +l[1:2] ## une liste de longueur 2 +l[1] ## une liste de longueur 1 +``` + +## Exportation et sauvegarde de données tabulaires {#sec:exportandsave} + +Nous avons vu comment lire une feuille de calcul textuelle dans R à l'aide de la famille de fonctions +`read.table`. Pour exporter un `data.frame` vers une feuille de calcul texte +, nous pouvons utiliser l'ensemble de fonctions `write.table` +(`write.csv`, `write.delim`, ...). Ils prennent tous la variable à +exportée et le fichier vers lequel exporter. Par exemple, pour exporter les données +`rna` vers le fichier `my_rna.csv` dans le répertoire `data_output` +, nous exécuterions : + +```{r, eval=FALSE, purl=TRUE} +write.csv(rna, file = "data_output/my_rna.csv") +``` + +This new csv file can now be shared with other collaborators who +aren't familiar with R. Note that even though there are commas in some of +the fields in the `data.frame` (see for example the "product" column), R will +by default surround each field with quotes, and thus we will be able to +read it back into R correctly, despite also using commas as column +separators. + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Données tabulaires dans R + +:::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/fr/episodes/30-dplyr.Rmd b/locale/fr/episodes/30-dplyr.Rmd new file mode 100644 index 000000000..7be73dca5 --- /dev/null +++ b/locale/fr/episodes/30-dplyr.Rmd @@ -0,0 +1,1047 @@ +--- +source: Rmd +title: Manipulation et analyse de données avec dplyr +teaching: 75 +exercises: 75 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Décrivez l'objectif des packages **`dplyr`** et **`tidyr`**. +- Décrivez plusieurs de leurs fonctions extrêmement utiles pour + manipuler des données. +- Décrivez le concept d'un format de tableau large et long, et voyez + comment remodeler un bloc de données d'un format à l'autre. +- Montrez comment joindre des tables. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- Analyse de données dans R à l'aide du méta-paquet Tidyverse + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +```{r loaddata_dplyr2, echo=FALSE, purl=FALSE, message=FALSE} +if (!file.exists("data/rnaseq.csv")) +download.file(url = "https://github.com/carpentries-incubator/bioc-intro/raw/main/episodes/data/rnaseq.csv", + destfile = "data/rnaseq.csv") +``` + +> Cet épisode est basé sur la leçon _Analyse des données et +> Visualisation dans R pour les écologistes_ de Data Carpentries. + +## Manipulation des données à l'aide de **`dplyr`** et **`tidyr`** + +Le sous-ensemble entre crochets est pratique, mais il peut être fastidieux et difficile à +lire, en particulier pour les opérations compliquées. + +Certains packages peuvent grandement faciliter notre tâche lorsque nous manipulons des données. +Les packages dans R sont essentiellement des ensembles de fonctions supplémentaires qui vous permettent +de faire plus de choses. Les fonctions que nous avons utilisées jusqu'à présent, comme `str()` ou +`data.frame()`, sont intégrées à R ; Le chargement de packages peut vous donner accès à d'autres +fonctions spécifiques. Avant d'utiliser un package pour la première fois, vous devez l'installer +sur votre machine, puis vous devez l'importer à chaque +session R suivante lorsque vous en avez besoin. + +- Le package **`dplyr`** fournit des outils puissants pour les tâches de manipulation de données. + Il est conçu pour fonctionner directement avec des trames de données, avec de nombreuses tâches de manipulation + optimisées. + +- Comme nous le verrons plus loin, nous souhaitons parfois qu'un bloc de données soit remodelé pour pouvoir + effectuer des analyses spécifiques ou pour la visualisation. Le package **`tidyr`** résout + ce problème courant de remodelage des données et fournit des outils pour manipuler les + données de manière ordonnée. + +Pour en savoir plus sur **`dplyr`** et **`tidyr`** après l'atelier, +vous voudrez peut-être consulter ceci transformation de données pratique avec +\*\* +et ceci celui sur +. + +- Le package **`tidyverse`** est un "package parapluie" qui installe + plusieurs packages utiles pour l'analyse des données qui fonctionnent bien ensemble, + tels que **`tidyr`**, \* \*`dplyr`\*\*, **`ggplot2`**, **`tibble`**, etc. + Ces packages nous aident à travailler et à interagir avec les données. + Ils nous permettent de faire beaucoup de choses avec vos données, comme le sous-ensemble, la transformation, la + visualisation, etc. + +Si vous avez effectué la configuration, vous devriez déjà avoir installé le package Tidyverse. +Vérifiez si vous l'avez en essayant de le charger depuis la bibliothèque : + +```{r, message=FALSE, purl=TRUE} +## load the tidyverse packages, incl. dplyr +library("tidyverse") +``` + +Si vous recevez un message d'erreur `il n'y a pas de package appelé 'tidyverse'` alors vous n'avez pas +installé le package pour cette version de R. Pour installer le package **`tidyverse`**, tapez : + +```{r, eval=FALSE, purl=TRUE} +BiocManager::install("tidyverse") +``` + +Si vous avez dû installer le package **`tidyverse`**, n'oubliez pas de le charger dans cette session R en utilisant la commande `library()` ci-dessus ! + +## Chargement de données avec Tidyverse + +Instead of `read.csv()`, we will read in our data using the `read_csv()` +function (notice the `_` instead of the `.`), from the tidyverse2 package +**`readr`**. + +```{r, message=FALSE, purl=TRUE} +rna <- read_csv("data/rnaseq.csv") + +## view the data +rna +``` + +Notez que la classe des données est désormais appelée « tibble ». + +Tibbles modifie certains des comportements des objets de trame de données que nous avons introduits dans le +précédemment. La structure des données est très similaire à une trame de données. Pour nos besoins +, les seules différences sont les suivantes : + +1. Il affiche le type de données de chaque colonne sous son nom. + Notez que \<`dbl`\> est un type de données défini pour contenir des valeurs numériques avec + points décimaux. + +2. Il imprime uniquement les premières lignes de données et seulement autant de colonnes que peuvent contenir + un écran. + +Nous allons maintenant apprendre certaines des fonctions **`dplyr`** les plus courantes : + +- `select()` : sous-ensemble de colonnes +- `filter()` : sous-ensemble de lignes sur conditions +- `mutate()` : crée de nouvelles colonnes en utilisant les informations d'autres colonnes +- `group_by()` et `summarise()` : créent des statistiques récapitulatives sur des données groupées +- `arrange()` : trier les résultats +- `count()` : compte les valeurs discrètes + +## Sélection de colonnes et filtrage de lignes + +Pour sélectionner les colonnes d'un bloc de données, utilisez `select()`. Le premier argument +de cette fonction est la trame de données (`rna`), et les arguments +suivants sont les colonnes à conserver. + +```{r, purl=TRUE} +select(rna, gene, sample, tissue, expression) +``` + +Pour sélectionner toutes les colonnes _sauf_ certaines, mettez un "-" devant +la variable pour l'exclure. + +```{r, purl=TRUE} +select(rna, -tissue, -organism) +``` + +Cela sélectionnera toutes les variables de `rna` sauf `tissu` +et `organism`. + +Pour choisir des lignes en fonction d'un critère spécifique, utilisez `filter()` : + +```{r, purl=TRUE} +filter(rna, sex == "Male") +filter(rna, sex == "Male" & infection == "NonInfected") +``` + +Imaginons maintenant que nous nous intéressions aux homologues humains des gènes +de souris analysés dans cet ensemble de données. Ces informations se trouvent dans la +dernière colonne du tibble `rna`, nommée +`hsapiens_homolog_associated_gene_name`. Pour le visualiser facilement, nous +allons créer un nouveau tableau contenant uniquement les 2 colonnes `gene` et +`hsapiens_homolog_associated_gene_name`. + +```{r} +genes <- select(rna, gene, hsapiens_homolog_associated_gene_name) +genes +``` + +Certains gènes de souris n'ont pas d'homologues humains. Ceux-ci peuvent être récupérés en utilisant +`filter()` et la fonction `is.na()`, qui détermine si +quelque chose est un `NA`. + +```{r, purl=TRUE} +filter(genes, is.na(hsapiens_homolog_associated_gene_name)) +``` + +Si on veut conserver uniquement les gènes de souris qui ont un homologue humain, on peut +insérer un "!" symbole qui annule le résultat, nous demandons donc +chaque ligne où hsapiens\_homolog\_associated\_gene\_name _n'est pas_ un +`NA`. + +```{r, purl=TRUE} +filter(genes, !is.na(hsapiens_homolog_associated_gene_name)) +``` + +## Tuyaux + +Et si vous souhaitez sélectionner et filtrer en même temps ? Il existe trois +façons de procéder : utiliser des étapes intermédiaires, des fonctions imbriquées ou des tuyaux. + +Avec des étapes intermédiaires, vous créez un bloc de données temporaire et l'utilisez +comme entrée de la fonction suivante, comme ceci : + +```{r, purl=TRUE} +rna2 <- filter(rna, sex == "Male") +rna3 <- select(rna2, gene, sample, tissue, expression) +rna3 +``` + +Ceci est lisible, mais peut encombrer votre espace de travail avec de nombreux +objets intermédiaires que vous devez nommer individuellement. Avec plusieurs étapes +, cela peut être difficile à suivre. + +Vous pouvez également imbriquer des fonctions (c'est-à-dire une fonction dans une autre), +comme ceci : + +```{r, purl=TRUE} +rna3 <- select(filter(rna, sex == "Male"), gene, sample, tissue, expression) +rna3 +``` + +C'est pratique, mais peut être difficile à lire si trop de fonctions sont imbriquées, car +R évalue l'expression de l'intérieur vers l'extérieur (dans ce cas, filtrer, puis sélectionner). + +La dernière option, _pipes_, est un ajout récent à R. Pipes vous permet de prendre +la sortie d'une fonction et de l'envoyer directement à la suivante, ce qui est utile +lorsque vous devez faire beaucoup de choses dans le même ensemble de données. + +Les tuyaux dans R ressemblent à `%>%` (mis à disposition via le package **`magrittr`** +) ou `|>` (via la base R). If you use RStudio, you can type +the pipe with Ctrl + Shift + M if you +have a PC or Cmd + Shift + M if you +have a Mac. + +Dans le code ci-dessus, nous utilisons le tube pour envoyer l'ensemble de données `rna` d'abord +via `filter()` pour conserver les lignes où `sex` est Homme, puis via +`select()` pour conserver uniquement les colonnes `gène`, `échantillon`, `tissu` et +`expression`. + +Le tube `%>%` prend l'objet à sa gauche et le passe directement comme +le premier argument de la fonction à sa droite, nous n'avons pas besoin de +inclure explicitement le bloc de données comme un argument pour les fonctions `filter()` et +`select()`. + +```{r, purl=TRUE} +rna %>% + filter(sex == "Male") %>% + select(gene, sample, tissue, expression) +``` + +Certains trouveront peut-être utile de lire le tube comme le mot « alors ». Par exemple, +dans l'exemple ci-dessus, nous avons pris la trame de données `rna`, _puis_ nous avons `filtré` +pour les lignes avec `sex == "Male"`, _puis_ nous avons « sélectionné les colonnes « gène », « échantillon », +« tissu » et « expression ». + +Les fonctions **`dplyr`** en elles-mêmes sont quelque peu simples, mais en +les combinant dans des flux de travail linéaires avec le tube, nous pouvons accomplir +des manipulations plus complexes de trames de données. + +Si nous voulons créer un nouvel objet avec cette version plus petite des données, nous pouvons +lui attribuer un nouveau nom : + +```{r, purl=TRUE} +rna3 <- rna %>% + filter(sex == "Male") %>% + select(gene, sample, tissue, expression) + +rna3 +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi: + +À l'aide de tuyaux, sous-ensemblez les données `rna` pour conserver les observations chez les souris femelles au temps 0, +où le gène a une expression supérieure à 50 000, et ne conservez que les colonnes +`gene`, `sample `, `time`, `expression` et `age`. + +::::::::::::::: solution + +## Solution + +```{r} +rna %>% + filter(expression > 50000, + sex == "Female", + time == 0 ) %>% + select(gene, sample, time, expression, age) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Subir une mutation + +Vous souhaiterez fréquemment créer de nouvelles colonnes basées sur les valeurs des colonnes +existantes, par exemple pour effectuer des conversions d'unités ou pour trouver le rapport des valeurs dans deux colonnes +. Pour cela, nous utiliserons `mutate()`. + +Pour créer une nouvelle colonne de temps en heures : + +```{r, purl=TRUE} +rna %>% + mutate(time_hours = time * 24) %>% + select(time, time_hours) +``` + +Vous pouvez également créer une deuxième nouvelle colonne basée sur la première nouvelle colonne dans le même appel de `mutate()` : + +```{r, purl=TRUE} +rna %>% + mutate(time_hours = time * 24, + time_mn = time_hours * 60) %>% + select(time, time_hours, time_mn) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi + +Créez un nouveau bloc de données à partir des données `rna` qui répond aux critères +suivants : contient uniquement le `gène`, le `nom_chromosome`, +`phenotype_description`, `sample` et `expression` Colonnes. Les valeurs de l'expression +doivent être transformées en log. Cette trame de données doit +contenir uniquement des gènes situés sur les chromosomes sexuels, associés à un phénotype +\_description, et avec une expression log supérieure à 5. + +**Astuce** : réfléchissez à la façon dont les commandes doivent être ordonnées pour produire +ce bloc de données ! + +::::::::::::::: solution + +## Solution + +```{r, eval=TRUE, purl=TRUE} +rna %>% + mutate(expression = log(expression)) %>% + select(gene, chromosome_name, phenotype_description, sample, expression) %>% + filter(chromosome_name == "X" | chromosome_name == "Y") %>% + filter(!is.na(phenotype_description)) %>% + filter(expression > 5) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Analyse de données fractionnée-appliquée-combinée + +De nombreuses tâches d'analyse de données peuvent être abordées à l'aide du paradigme +_split-apply-combine_ : divisez les données en groupes, appliquez une analyse +à chaque groupe, puis combinez les résultats. **`dplyr`** +rend cela très facile grâce à l'utilisation de la fonction `group_by()`. + +```{r} +rna %>% + group_by(gene) +``` + +La fonction `group_by()` n'effectue aucun traitement de données, elle +regroupe les données en sous-ensembles : dans l'exemple ci-dessus, notre +`tibble` initial de `r nrow(rna)` les observations sont divisées en +`r length(unique(rna$gene))` en fonction de la variable `gene`. + +On pourrait de même décider de regrouper les tibbles par échantillons : + +```{r} +rna %>% + group_by(sample) +``` + +Ici, notre `tibble` initial d'observations `r nrow(rna)` est divisé en groupes +`r length(unique(rna$sample))` en fonction de la variable `sample`. + +Une fois les données regroupées, les opérations suivantes seront +appliquées sur chaque groupe indépendamment. + +### La fonction `summaris()` + +`group_by()` est souvent utilisé avec `summarise()`, qui +réduit chaque groupe en un résumé sur une seule ligne de ce groupe. + +`group_by()` prend comme arguments les noms de colonnes qui contiennent les variables +**catégorielles** pour lesquelles vous souhaitez calculer les statistiques récapitulatives +. Donc, pour calculer l'expression moyenne par gène : + +```{r} +rna %>% + group_by(gene) %>% + summarise(mean_expression = mean(expression)) +``` + +Nous pourrions également vouloir calculer les niveaux d’expression moyens de tous les gènes dans chaque échantillon : + +```{r} +rna %>% + group_by(sample) %>% + summarise(mean_expression = mean(expression)) +``` + +Mais on peut aussi regrouper par plusieurs colonnes : + +```{r} +rna %>% + group_by(gene, infection, time) %>% + summarise(mean_expression = mean(expression)) +``` + +Une fois les données regroupées, vous pouvez également résumer plusieurs variables en même temps +(et pas nécessairement sur la même variable). Par exemple, nous pourrions ajouter une colonne +indiquant l'expression médiane par gène et par condition : + +```{r, purl=TRUE} +rna %>% + group_by(gene, infection, time) %>% + summarise(mean_expression = mean(expression), + median_expression = median(expression)) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi + +Calculer le niveau d’expression moyen du gène « Dok3 » par points temporels. + +::::::::::::::: solution + +## Solution + +```{r, purl=TRUE} +rna %>% + filter(gene == "Dok3") %>% + group_by(time) %>% + summarise(mean = mean(expression)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +### Compte + +Lorsque nous travaillons avec des données, nous souhaitons souvent connaître le nombre d'observations trouvées +pour chaque facteur ou combinaison de facteurs. Pour cette tâche, **`dplyr`** fournit +`count()`. Par exemple, si nous voulions compter le nombre de lignes de données pour +chaque échantillon infecté et non infecté, nous ferions : + +```{r, purl=TRUE} +rna %>% + count(infection) +``` + +La fonction `count()` est un raccourci pour quelque chose que nous avons déjà vu : regrouper par une variable et le résumer en comptant le nombre d'observations dans ce groupe. En d'autres termes, « rna %>% count(infection) » équivaut à : + +```{r, purl=TRUE} +rna %>% + group_by(infection) %>% + summarise(n = n()) +``` + +L'exemple précédent montre l'utilisation de `count()` pour compter le nombre de lignes/observations +pour _un_ facteur (c'est-à-dire `infection`). +Si nous voulions compter une _combinaison de facteurs_, telle que `infection` et `time`, +nous spécifierions le premier et le deuxième facteur comme arguments de `count()` : + +```{r, purl=TRUE} +rna %>% + count(infection, time) +``` + +ce qui équivaut à ceci : + +```{r, purl=TRUE} +rna %>% + group_by(infection, time) %>% + summarise(n = n()) +``` + +Il est parfois utile de trier le résultat pour faciliter les comparaisons. +Nous pouvons utiliser `arrange()` pour trier le tableau. +Par exemple, nous pourrions vouloir organiser le tableau ci-dessus par heure : + +```{r, purl=TRUE} +rna %>% + count(infection, time) %>% + arrange(time) +``` + +ou par comptages : + +```{r, purl=TRUE} +rna %>% + count(infection, time) %>% + arrange(n) +``` + +Pour trier par ordre décroissant, nous devons ajouter la fonction `desc()` : + +```{r, purl=TRUE} +rna %>% + count(infection, time) %>% + arrange(desc(n)) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi + +1. Combien de gènes ont été analysés dans chaque échantillon ? +2. Utilisez `group_by()` et `summarise()` pour évaluer la profondeur de séquençage (la somme de tous les comptes) dans chaque échantillon. Quel échantillon a la profondeur de séquençage la plus élevée ? +3. Choisissez un échantillon et évaluez le nombre de gènes par biotype. +4. Identifiez les gènes associés à la description du phénotype « méthylation anormale de l’ADN » et calculez leur expression moyenne (en log) au temps 0, au temps 4 et au temps 8. + +::::::::::::::: solution + +## Solution + +```{r} +## 1. +rna %>% + count(sample) +## 2. +rna %>% + group_by(sample) %>% + summarise(seq_depth = sum(expression)) %>% + arrange(desc(seq_depth)) +## 3. +rna %>% + filter(sample == "GSM2545336") %>% + count(gene_biotype) %>% + arrange(desc(n)) +## 4. +rna %>% + filter(phenotype_description == "abnormal DNA methylation") %>% + group_by(gene, time) %>% + summarise(mean_expression = mean(log(expression))) %>% + arrange() +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Remodeler les données + +Dans le tibble `rna`, les lignes contiennent des valeurs d'expression (l'unité) qui sont +associées à une combinaison de 2 autres variables : `gene` et `sample`. + +Toutes les autres colonnes correspondent à des variables décrivant soit +l'échantillon (organisme, âge, sexe, ...) soit le gène (gène\_biotype, ENTREZ\_ID, produit, ...). +Les variables qui ne changent pas avec les gènes ou avec les échantillons auront la même valeur dans toutes les lignes. + +```{r} +rna %>% + arrange(gene) +``` + +Cette structure est appelée « format long », car une colonne contient toutes les valeurs, +et d'autres colonnes répertorient le contexte de la valeur. + +Dans certains cas, le « format long » n'est pas vraiment « lisible par l'homme », et un autre format, +un « format large » est préféré, comme manière plus compacte de représenter les données. +This is typically the case with gene expression values that scientists are used to +look as matrices, were rows represent genes and columns represent samples. + +Dans ce format, il deviendrait donc simple +d'explorer la relation entre les niveaux d'expression génique au sein et +entre les échantillons. + +```{r, echo=FALSE} +rna %>% + select(gene, sample, expression) %>% + pivot_wider(names_from = sample, + values_from = expression) +``` + +Pour convertir les valeurs d'expression génique de `rna` en un format large, +nous devons créer une nouvelle table où les valeurs de la colonne `sample` deviendraient +les noms des variables de colonne. + +The key point here is that we are still following +a tidy data structure, but we have **reshaped** the data according to +the observations of interest: expression levels per gene instead +of recording them per gene and per sample. + +La transformation inverse serait de transformer les noms de colonnes en valeurs +d'une nouvelle variable. + +Nous pouvons effectuer ces deux transformations avec deux fonctions `tidyr`, +`pivot_longer()` et `pivot_wider()` (voir +[ici](https://tidyr.tidyverse.org /dev/articles/pivot.html) pour +détails). + +### Pivoter les données dans un format plus large + +Sélectionnons les 3 premières colonnes de `rna` et utilisons `pivot_wider()` +pour transformer les données en grand format. + +```{r, purl=TRUE} +rna_exp <- rna %>% + select(gene, sample, expression) +rna_exp +``` + +`pivot_wider` prend trois arguments principaux : + +1. les données à transformer ; +2. le `names_from` : la colonne dont les valeurs deviendront de nouveaux noms de colonne +  ; +3. les `values_from` : la colonne dont les valeurs rempliront les nouvelles colonnes + . + +```{r, fig.cap="Grand pivot des données `rna`.", echo=FALSE, message=FALSE} +knitr::include_graphics("fig/pivot_wider.png") + +``` + +```{r, purl=TRUE} +rna_wide <- rna_exp %>% + pivot_wider(names_from = sample, + values_from = expression) +rna_wide +``` + +Notez que par défaut, la fonction `pivot_wider()` ajoutera `NA` pour les valeurs manquantes. + +Imaginons que, pour une raison quelconque, nous ayons des valeurs d'expression manquantes pour certains gènes +dans certains échantillons. In the following fictive example, the gene Cyp2d22 has only +one expression value, in GSM2545338 sample. + +```{r, purl=TRUE} +rna_with_missing_values <- rna %>% + select(gene, sample, expression) %>% + filter(gene %in% c("Asl", "Apod", "Cyp2d22")) %>% + filter(sample %in% c("GSM2545336", "GSM2545337", "GSM2545338")) %>% + arrange(sample) %>% + filter(!(gene == "Cyp2d22" & sample != "GSM2545338")) +rna_with_missing_values +``` + +Par défaut, la fonction `pivot_wider()` ajoutera `NA` pour les valeurs +manquantes. Ceci peut être paramétré avec l'argument `values_fill` de +la fonction `pivot_wider()`. + +```{r, purl=TRUE} +rna_with_missing_values %>% + pivot_wider(names_from = échantillon, + values_from = expression) + +rna_with_missing_values %>% + pivot_wider(names_from = échantillon, + values_from = expression, + valeurs_fill = 0) +``` + +### Pivoter les données dans un format plus long + +Dans la situation inverse, nous utilisons les noms de colonnes et les transformons en +une paire de nouvelles variables. Une variable représente les noms de colonnes sous forme de valeurs +, et l'autre variable contient les valeurs précédemment +associées aux noms de colonnes. + +`pivot_longer()` prend quatre arguments principaux : + +1. les données à transformer ; +2. le `names_to` : le nouveau nom de colonne que nous souhaitons créer et remplir avec les + noms de colonnes actuels ; +3. les `values_to` : le nouveau nom de colonne que nous souhaitons créer et remplir avec + valeurs actuelles ; +4. les noms des colonnes à utiliser pour renseigner les variables `names_to` et + `values_to` (ou à supprimer). + +```{r, fig.cap="Pivot long des données `rna`.", echo=FALSE, message=FALSE} +knitr::include_graphics("fig/pivot_longer.png") + +``` + +To recreate `rna_long` from `rna_wide` we would create a key +called `sample` and value called `expression` and use all columns +except `gene` for the key variable. Here we drop `gene` column +with a minus sign. + +Notice how the new variable names are to be quoted here. + +```{r} +rna_long <- rna_wide %>% + pivot_longer(names_to = "sample", + values_to = "expression", + -gene) +rna_long +``` + +Nous aurions également pu utiliser une spécification indiquant les colonnes à +inclure. Cela peut être utile si vous disposez d'un grand nombre de colonnes d'identification +, et il est plus facile de spécifier ce qu'il faut rassembler que ce qu'il faut laisser +seul. Ici, la fonction `starts_with()` peut aider à récupérer des exemples de noms +sans avoir à tous les lister ! +Une autre possibilité serait d'utiliser l'opérateur `:` ! + +```{r} +rna_wide %>% + pivot_longer(names_to = "sample", + values_to = "expression", + cols = start_with("GSM")) +rna_wide %> % + pivot_longer(names_to = "échantillon", + valeurs_to = "expression", + GSM2545336:GSM2545380) +``` + +Notez que si nous avions des valeurs manquantes dans le format large, le « NA » serait +inclus dans le nouveau format long. + +Souvenez-vous de notre précédent tibble fictif contenant des valeurs manquantes : + +```{r} +rna_with_missing_values + +wide_with_NA <- rna_with_missing_values %>% + pivot_wider(names_from = sample, + values_from = expression) +wide_with_NA + +wide_with_NA %>% + pivot_longer(names_to = "sample", + values_to = "expression", + -gene) +``` + +Passer à des formats plus larges et plus longs peut être un moyen utile d'équilibrer un ensemble de données +afin que chaque réplique ait la même composition. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Question + +A partir de la table arn, utilisez la fonction `pivot_wider()` pour créer +un tableau grand format donnant les niveaux d'expression génique chez chaque souris. +Utilisez ensuite la fonction `pivot_longer()` pour restaurer un tableau au format long. + +::::::::::::::: solution + +## Solution + +```{r, answer=TRUE, purl=TRUE} +rna1 <- rna %>% +select(gène, souris, expression) %>% +pivot_wider(names_from = souris, valeurs_from = expression) +rna1 + +rna1 %>% +pivot_longer(names_to = "mouse_id", valeurs_to = "counts", -gene) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Question + +Sous-ensemble de gènes situés sur les chromosomes X et Y de la trame de données « rna » et +répartissent la trame de données avec « sexe » en colonnes, « nom_chromosome » en +lignes et l'expression moyenne des gènes localisés dans chaque chromosome comme valeurs, +comme dans le tableau suivant : + +```{r, echo=FALSE, message=FALSE} +knitr::include_graphics("fig/Exercise_pivot_W.png") +``` + +Il faudra résumer avant de remodeler ! + +::::::::::::::: solution + +## Solution + +Calculons d'abord le niveau d'expression moyen des gènes liés X et Y à partir de +échantillons mâles et femelles... + +```{r} + arn %>% + filter(chromosome_name == "Y" | chromosome_name == "X") %>% + group_by(sex, chromosome_name) %>% + résumé(moyenne = moyenne(expression)) +``` + +Et faites pivoter le tableau au format large + +```{r, answer=TRUE, purl=TRUE} +rna_1 <- rna %>% + filter(chromosome_name == "Y" | chromosome_name == "X") %>% + group_by(sex, chromosome_name) %>% + summarise(mean = moyenne(expression)) %>% + pivot_wider(names_from = sexe, + valeurs_from = moyenne) + +rna_1 +``` + +Maintenant, prenez cette trame de données et transformez-la avec `pivot_longer()` afin que +chaque ligne soit une combinaison unique de `chromosome_name` par `gender`. + +```{r, answer=TRUE, purl=TRUE} +rna_1 %>% + pivot_longer(names_to = "gender", + valeurs_to = "mean", + -chromosome_name) + +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Question + +Utilisez l'ensemble de données `rna` pour créer une matrice d'expression où chaque ligne +représente les niveaux d'expression moyens des gènes et les colonnes représentent +les différents moments. + +::::::::::::::: solution + +## Solution + +Calculons d'abord l'expression moyenne par gène et par temps + +```{r} +arn %>% + group_by(gène, temps) %>% + résumé(mean_exp = moyenne(expression)) +``` + +avant d'utiliser la fonction pivot\_wider() + +```{r} +rna_time <- rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) +rna_time +``` + +Notez que cela génère un tibble avec certains noms de colonnes commençant par un nombre. +Si nous voulions sélectionner la colonne correspondant aux points temporels, +nous ne pourrions pas utiliser directement les noms de colonnes... Que se passe-t-il lorsque l'on sélectionne la colonne 4 ? + +```{r} +rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) %>% + select(gene, 4) +``` + +Pour sélectionner le timepoint 4, il faudrait citer le nom de la colonne, avec des backticks "\\`" + +```{r} +rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) %>% + select(gene, `4`) +``` + +Une autre possibilité serait de renommer la colonne, +en choisissant un nom qui ne commence pas par un chiffre : + +```{r} +rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) %>% + rename("time0" = `0`, "time4" = `4`, "time8" = `8`) %>% + select(gene, time4) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Question + +Utilisez la trame de données précédente contenant les niveaux d'expression moyens par point temporel et créez +une nouvelle colonne contenant les changements de pli entre le point temporel 8 et le point temporel 0, et les changements de pli +entre le point temporel 8 et le point temporel 4. +Convertissez ce tableau en un tableau au format long regroupant les changements de pli calculés. + +::::::::::::::: solution + +## Solution + +À partir du tibble rna\_time : + +```{r} +arn_time +``` + +Calculer les changements de plis : + +```{r} +rna_time %>% + muter (time_8_vs_0 = `8` / `0`, time_8_vs_4 = `8` / `4`) +``` + +Et utilisez la fonction pivot\_longer() : + +```{r} +rna_time %>% + mutate(time_8_vs_0 = `8` / `0`, time_8_vs_4 = `8` / `4`) %>% + pivot_longer(names_to = "comparisons", + values_to = "Fold_changes", + time_8_vs_0:time_8_vs_4) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +## Joindre des tables + +Dans de nombreuses situations réelles, les données sont réparties sur plusieurs tables. +Cela se produit généralement parce que différents types d’informations sont +collectés à partir de différentes sources. + +Il peut être souhaitable que certaines analyses combinent les données de deux ou plusieurs tables +en une seule trame de données basée sur une colonne qui serait commune +à toutes les tables. + +Le package `dplyr` fournit un ensemble de fonctions de jointure pour combiner deux trames de données +basées sur des correspondances dans des colonnes spécifiées. Ici, nous +fournissons une brève introduction aux jointures. Pour en savoir plus, veuillez +vous référer au chapitre sur les jointures de table +. La +Data Transformation Cheat +Sheet +fournit également un bref aperçu sur les jointures de table. + +Nous allons illustrer la jointure en utilisant une petite table, `rna_mini` que +nous allons créer en sous-définissant la table `rna` d'origine, en ne gardant que 3 +colonnes et 10 lignes. + +```{r} +rna_mini <- rna %>% + select(gène, échantillon, expression) %>% + head(10) +rna_mini +``` + +Le deuxième tableau, `annot1`, contient 2 colonnes, gene et +gene\_description. Vous pouvez soit +[télécharger annot1.csv](https://carpentries-incubator.github.io/bioc-intro/data/annot1.csv) +en cliquant sur le lien puis en vous déplaçant dans le dossier `data/`, ou +vous pouvez utiliser le code R ci-dessous pour le télécharger directement dans le dossier. + +```{r, message=FALSE} +download.file(url = "https://carpentries-incubator.github.io/bioc-intro/data/annot1.csv", + destfile = "data/annot1.csv") +annot1 <- read_csv(file = "data/annot1.csv") +annot1 +``` + +Nous voulons maintenant joindre ces deux tables en une seule contenant toutes les +variables en utilisant la fonction `full_join()` du package `dplyr`. La fonction +trouvera automatiquement la variable commune correspondant aux colonnes +de la première et de la deuxième table. Dans ce cas, « gène » est la variable commune +. Ces variables sont appelées clés. Les clés sont utilisées pour faire correspondre +observations dans différentes tables. + +```{r} +full_join(rna_mini, annot1) +``` + +Dans la vraie vie, les annotations génétiques sont parfois étiquetées différemment. + +La table `annot2` est exactement la même que `annot1` sauf que la variable +contenant les noms de gènes est étiquetée différemment. Encore une fois, soit +[télécharger annot2.csv](https://carpentries-incubator.github.io/bioc-intro/data/annot2.csv) +vous-même et déplacez-le vers `data/ ` ou utilisez le code R ci-dessous. + +```{r, message=FALSE} +download.file(url = "https://carpentries-incubator.github.io/bioc-intro/data/annot2.csv", + destfile = "data/annot2.csv") +annot2 <- read_csv(file = "data/annot2.csv") +annot2 +``` + +Si aucun des noms de variables ne correspond, nous pouvons définir manuellement les variables +à utiliser pour la correspondance. Ces variables peuvent être définies en utilisant +l'argument `by`, comme indiqué ci-dessous avec les tables `rna_mini` et `annot2`. + +```{r} +full_join(rna_mini, annot2, by = c("gene" = "external_gene_name")) +``` + +Comme on peut le voir ci-dessus, le nom de variable de la première table est conservé +dans celle jointe. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi: + +Téléchargez la table `annot3` en cliquant sur +[ici](https://carpentries-incubator.github.io/bioc-intro/data/annot3.csv) +et placez la table dans votre Dépôt de données. À l'aide de la fonction `full_join()` +, joignez les tables `rna_mini` et `annot3`. Que s'est-il passé pour les gènes +_Klk6_, _mt-Tf_, _mt-Rnr1_, _mt-Tv_, _mt-Rnr2_ et _mt-Tl1_ ? + +::::::::::::::: solution + +## Solution + +```{r, message=FALSE} +annot3 <- read_csv("data/annot3.csv") +full_join(rna_mini, annot3) +``` + +Les gènes _Klk6_ ne sont présents que dans `rna_mini`, tandis que les gènes _mt-Tf_, _mt-Rnr1_, _mt-Tv_, +_mt-Rnr2_ et _mt-Tl1_ sont présent uniquement dans la table `annot3`. Leurs valeurs respectives pour les variables +du tableau ont été codées comme manquantes. + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Exporter des données + +Maintenant que vous avez appris à utiliser `dplyr` pour extraire des informations de +ou résumer vos données brutes, vous souhaiterez peut-être exporter ces nouveaux ensembles de données pour les partager +avec vos collaborateurs ou pour les archiver. + +Semblable à la fonction `read_csv()` utilisée pour lire les fichiers CSV dans R, il existe +une fonction `write_csv()` qui génère des fichiers CSV à partir de trames de données. + +Avant d'utiliser `write_csv()`, nous allons créer un nouveau dossier, `data_output`, +dans notre répertoire de travail qui stockera cet ensemble de données généré. Nous ne voulons pas que +écrive les ensembles de données générés dans le même répertoire que nos données brutes. +C'est une bonne pratique de les garder séparés. Le dossier `data` ne doit contenir que +les données brutes et non modifiées, et doit être laissé seul pour nous assurer que nous ne supprimons pas +ou ne le modifions pas. En revanche, notre script générera le contenu du répertoire `data_output` +, donc même si les fichiers qu'il contient sont supprimés, nous pouvons toujours +les régénérer. + +Utilisons `write_csv()` pour sauvegarder la table rna\_wide que nous avons créée précédemment. + +```{r, purl=TRUE, eval=FALSE} +write_csv(rna_wide, file = "data_output/rna_wide.csv") +``` + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Données tabulaires dans R utilisant le méta-paquet Tidyverse + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/fr/episodes/40-visualization.Rmd b/locale/fr/episodes/40-visualization.Rmd new file mode 100644 index 000000000..88ef4a55e --- /dev/null +++ b/locale/fr/episodes/40-visualization.Rmd @@ -0,0 +1,1107 @@ +--- +source: Rmd +title: Visualisation de données +teaching: 60 +exercises: 60 +--- + +```{r loaddata_vis, echo=FALSE, purl=FALSE, message=FALSE} +if (!file.exists("data/rnaseq.csv")) +download.file(url = "https://github.com/carpentries-incubator/bioc-intro/raw/main/episodes/ data/rnaseq.csv", + destfile = "data/rnaseq.csv") +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Produisez des nuages de points, des boxplots, des tracés linéaires, etc. en utilisant ggplot. +- Définissez les paramètres de tracé universels. +- Décrivez ce qu'est le facettage et appliquez le facettage dans ggplot. +- Modifiez l'esthétique d'un tracé ggplot existant (y compris les étiquettes des axes et la couleur). +- Créez des tracés complexes et personnalisés à partir de données dans un bloc de données. + +:::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- Visualisation en R + +:::::::::::::::::::::::::::::::::::::::::::::::: + +```{r vis_setup, echo=FALSE} +arn <- read.csv("data/rnaseq.csv") +``` + +> Cet épisode est basé sur la leçon _Analyse des données et +> Visualisation dans R pour les écologistes_ de Data Carpentries. + +## Visualisation de données + +Nous commençons par charger les packages requis. **`ggplot2`** est inclus dans +le package **`tidyverse`**. + +```{r load-package, message=FALSE, purl=TRUE} +bibliothèque("tidyverse") +``` + +Si vous n'êtes pas encore dans l'espace de travail, chargez les données que nous avons enregistrées dans la leçon +précédente. + +```{r load-data, eval=FALSE, purl=TRUE} +arn <- read.csv("data/rnaseq.csv") +``` + +La Data Visualization Cheat + +couvrira les bases et les fonctionnalités plus avancées de ` ggplot2` et +aidera, en plus de servir de rappel, à obtenir un aperçu des +nombreuses représentations de données disponibles dans le package. Les didacticiels vidéo suivants +([partie 1](https://www.youtube.com/watch?v=h29g21z0a68) et +[2](https://www.youtube.com /watch?v=0m4yywqNPVY)) de Thomas Lin Pedersen +sont également très instructifs. + +## Tracer avec `ggplot2` + +`ggplot2` est un package de traçage qui simplifie la création de tracés +complexes à partir de données dans un bloc de données. Il fournit une interface +plus programmatique pour spécifier les variables à tracer, comment elles sont affichées, +et les propriétés visuelles générales. La fondation théorique qui prend en charge +le `ggplot2` est la _Grammar of Graphics_ (@Wilkinson :2005). En utilisant cette approche +, nous n'avons besoin que de changements minimes si les données sous-jacentes changent ou +si nous décidons de passer d'un diagramme à barres à un nuage de points. Cela aide à +créer des tracés de qualité de publication avec un minimum d'ajustements +et de peaufinages. + +Il existe un livre sur `ggplot2` (@ggplot2book) qui fournit un bon aperçu de +, mais il est obsolète. La 3ème édition est en préparation et sera +[disponible gratuitement en ligne](https://ggplot2-book.org/). La page Web `ggplot2` +([https://ggplot2.tidyverse.org](https://ggplot2.tidyverse.org)) fournit une documentation abondante. + +`ggplot2` fonctionne comme des données au format « long », c'est-à-dire une colonne pour +chaque dimension et une ligne pour chaque observation. Des données bien structurées +vous feront gagner beaucoup de temps lors de la création de chiffres avec `ggplot2`. + +Les graphiques ggplot sont construits étape par étape en ajoutant de nouveaux éléments. L'ajout de +couches de cette manière permet une grande flexibilité et une +personnalisation des tracés. + +> L'idée derrière la grammaire graphique est que vous pouvez construire chaque graphique +> à partir des 3 mêmes composants : (1) un ensemble de données, (2) un système de coordonnées, +> et (3) des géoms. — c'est-à-dire des marques visuelles qui représentent des points de données \[^trois\\_comp\\_ggplot2] + +[^three_comp_ggplot2]: Source : [Aide-mémoire pour la visualisation des données](https://raw.githubusercontent.com/rstudio/cheatsheets/main/data-visualization.pdf). + +Pour construire un ggplot, nous utiliserons le modèle de base suivant qui peut être +utilisé pour différents types de tracés : + +``` +ggplot(data = , mapping = aes()) + () +``` + +- utilisez la fonction `ggplot()` et liez le tracé à un cadre \*\*data + \*\* spécifique en utilisant l'argument `data` + +```{r, eval=FALSE} +ggplot(data = rna) +``` + +- définir un **mapping** (en utilisant la fonction esthétique (`aes`)), en + sélectionnant les variables à tracer et en spécifiant comment les présenter + dans le graphique, par exemple sous la forme x/ y positions ou caractéristiques telles que + taille, forme, couleur, etc. + +```{r, eval=FALSE} +ggplot(data = rna, mapping = aes(x = expression)) +``` + +- ajoutez '**geoms**' - géométries ou représentations graphiques des données + dans le tracé (points, lignes, barres). `ggplot2` propose de nombreuses + géométries différentes ; nous en utiliserons quelques-uns courants aujourd’hui, notamment : + + ``` + * `geom_point()` pour les nuages de points, les diagrammes de points, etc. + * `geom_histogram()` pour les histogrammes + * `geom_boxplot()` pour, eh bien, les boxplots ! + * `geom_line()` pour les lignes de tendance, les séries chronologiques, etc. + ``` + +Pour ajouter une géométrie au tracé, utilisez l'opérateur `+`. Utilisons d'abord +`geom_histogram()` : + +```{r first-ggplot, cache=FALSE, purl=TRUE} +ggplot(data = rna, mapping = aes(x = expression)) + + geom_histogram() +``` + +Le `+` dans le package `ggplot2` est particulièrement utile car il +vous permet de modifier les objets `ggplot` existants. Cela signifie que vous pouvez +facilement configurer des modèles de tracé et explorer facilement différents types de +tracés, de sorte que le tracé ci-dessus peut également être généré avec un code comme celui-ci : + +```{r, eval=FALSE, purl=TRUE} +# Assign plot to a variable +rna_plot <- ggplot(data = rna, + mapping = aes(x = expression)) + +# Draw the plot +rna_plot + geom_histogram() +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi + +Vous avez probablement remarqué un message automatique qui apparaît lorsque +dessine l'histogramme : + +```{r, echo=FALSE, fig.show="hide"} +ggplot(rna, aes(x = expression)) + + geom_histogram() +``` + +Modifiez les arguments `bins` ou `binwidth` de `geom_histogram()` en +changez le nombre ou la largeur des bacs. + +::::::::::::::: solution + +## Solution + +```{r, purl=TRUE} +# change bins +ggplot(rna, aes(x = expression)) + + geom_histogram(bins = 15) + +# change binwidth +ggplot(rna, aes(x = expression)) + + geom_histogram(binwidth = 2000) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +Nous pouvons observer ici que les données sont biaisées vers la droite. Nous pouvons appliquer la transformation +log2 pour avoir une distribution plus symétrique. Notez que nous +ajoutons ici une petite valeur constante (`+1`) pour éviter que les valeurs `-Inf` +soient renvoyées pour les valeurs d'expression égales à 0. + +```{r log-transfo, cache=FALSE, purl=TRUE} +arn <- arn %>% + muter(expression_log = log2(expression + 1)) +``` + +Si l'on dessine maintenant l'histogramme des expressions transformées en log2, la distribution +est en effet plus proche d'une distribution normale. + +```{r second-ggplot, cache=FALSE, purl=TRUE} +ggplot(rna, aes(x = expression_log)) + geom_histogram() +``` + +À partir de maintenant, nous travaillerons sur les valeurs d’expression transformées en log. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi + +Une autre façon de visualiser cette transformation est de considérer l’échelle +des observations. Par exemple, il peut être intéressant de changer l'échelle +de l'axe pour mieux répartir les observations dans l'espace de la parcelle +. Changer l'échelle des axes se fait de la même manière que +ajouter/modifier d'autres composants (c'est-à-dire en ajoutant progressivement des commandes +). Essayez de faire cette modification : + +- Représenter l'expression non transformée sur l'échelle log10 ; voir + `scale_x_log10()`. Comparez-le avec le graphique précédent. Pourquoi + des messages d'avertissement apparaissent-ils maintenant ? + +::::::::::::::: solution + +## Solution + +```{r, eval=TRUE, purl=TRUE, echo=TRUE} +ggplot(data = rna,mapping = aes(x = expression))+ + geom_histogram() + + scale_x_log10() +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +**Remarques** + +- Tout ce que vous mettez dans la fonction `ggplot()` peut être vu par n'importe quelle couche geom + que vous ajoutez (c'est-à-dire qu'il s'agit de paramètres de tracé globaux). Ce + inclut le mappage des axes x et y que vous avez configuré dans `aes()`. +- Vous pouvez également spécifier des mappages pour une géom donnée indépendamment des mappages + définis globalement dans la fonction `ggplot()`. +- Le signe `+` utilisé pour ajouter de nouveaux calques doit être placé à la fin de la ligne + contenant le calque _précédent_. If, instead, the `+` sign is + added at the beginning of the line containing the new layer, + `ggplot2` will not add the new layer and will return an error + message. + +```{r, eval=FALSE} +# This is the correct syntax for adding layers +rna_plot + + geom_histogram() + +# This will not add the new layer and will return an error message +rna_plot + + geom_histogram() +``` + +## Construire vos parcelles de manière itérative + +Nous allons maintenant dessiner un nuage de points avec deux variables continues et la fonction +`geom_point()`. Ce graphique représentera les changements de pli log2 +de l'expression comparant le temps 8 au temps 0 et le temps 4 au temps 0. +À cette fin, nous devons d'abord calculer les moyennes des valeurs d'expression +transformées en log par gène et par temps, puis le pli du log change en +en soustrayant les expressions du log moyen entre le temps 8 et le temps 0. et +entre le temps 4 et le temps 0. Notez que nous incluons également ici le biotype du gène +que nous utiliserons plus tard pour représenter les gènes. Nous enregistrerons +les changements de repli dans un nouveau bloc de données appelé `rna_fc.` + +```{r rna_fc, cache=FALSE, purl=TRUE} +rna_fc <- rna %>% select(gene, time, + gene_biotype, expression_log) %>% + group_by(gene, time, gene_biotype) %>% + summary(mean_exp = moyenne (expression_log)) %>% + pivot_wider(names_from = temps, + valeurs_from = moyenne_exp) %>% + mutate(time_8_vs_0 = `8` - `0`, time_4_vs_0 = `4` - `0`) + +``` + +Nous pouvons ensuite construire un ggplot avec l'ensemble de données nouvellement créé `rna_fc`. +Construire des parcelles avec `ggplot2` est généralement un processus itératif. Nous +commençons par définir l'ensemble de données que nous allons utiliser, tracer les axes et choisir une +géom : + +```{r create-ggplot-object, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point() +``` + +Ensuite, nous commençons à modifier ce tracé pour en extraire plus d’informations. +Par exemple, nous pouvons ajouter de la transparence (« alpha ») pour éviter le surtraçage : + +```{r adding-transparency, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point(alpha = 0.3) +``` + +On peut également ajouter des couleurs pour tous les points : + +```{r adding-colors, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point(alpha = 0.3, color = "blue") +``` + +Ou pour colorer différemment chaque gène du tracé, vous pouvez utiliser un vecteur comme +entrée dans l'argument **color**. `ggplot2` fournira une couleur +différente correspondant à différentes valeurs dans le vecteur. Voici un +exemple où nous colorons avec `gene_biotype` : + +```{r color-by-gene_biotype1, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point(alpha = 0.3, aes(color = gene_biotype)) + +``` + +Nous pouvons également spécifier les couleurs directement à l'intérieur du mappage fourni dans +la fonction `ggplot()`. Cela sera visible par toutes les couches géométriques et la cartographie +sera déterminée par les axes x et y définis dans `aes()`. + +```{r color-by-gene_biotype2, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0, + color = gene_biotype)) + + geom_point(alpha = 0.3) +``` + +Enfin, nous pourrions également ajouter une ligne diagonale avec la fonction `geom_abline()` + : + +```{r adding-diag, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0, + color = gene_biotype)) + + geom_point(alpha = 0.3) + + geom_abline(intercept = 0) +``` + +Notez que nous pouvons changer la couche géométrique de `geom_point` à +`geom_jitter` et les couleurs seront toujours déterminées par `gene_biotype`. + +```{r color-by-gene_biotype3, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0, + color = gene_biotype)) + + geom_jitter(alpha = 0.3) + + geom_abline(intercept = 0) +``` + +```{r, echo=FALSE, message=FALSE} +bibliothèque("hexbin") +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi + +Les nuages de points peuvent être des outils d’exploration utiles pour de petits ensembles de données. Pour les ensembles de données +avec un grand nombre d'observations, tels que l'ensemble de données `rna_fc` +, le surtraçage des points peut constituer une limitation des nuages de points. +Une stratégie pour gérer de tels paramètres consiste à utiliser le regroupement hexagonal d'observations +. L’espace de l’intrigue est divisé en hexagones. Chaque +hexagone se voit attribuer une couleur en fonction du nombre d'observations qui +tombent dans ses limites. + +- Pour utiliser le regroupement hexagonal dans `ggplot2`, installez d'abord le package R + `hexbin` depuis CRAN et chargez-le. + +- Utilisez ensuite la fonction `geom_hex()` pour produire la figure hexbin. + +- Quelles sont les forces et les faiblesses relatives d'un diagramme hexagonal + par rapport à un nuage de points ? Examinez le nuage de points ci-dessus + et comparez-le avec le diagramme hexagonal que vous avez créé. + +::::::::::::::: solution + +## Solution + +```{r, eval=FALSE, purl=TRUE} +install.packages("hexbin") +``` + +```{r, purl=TRUE} +library("hexbin") + +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_hex() + + geom_abline(intercept = 0) + +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi + +Utilisez ce que vous venez d'apprendre pour créer un nuage de points de `expression_log` +sur `sample` à partir de l'ensemble de données `rna` avec l'heure affichée dans +différentes couleurs. Est-ce une bonne façon d’afficher ce type de données ? + +::::::::::::::: solution + +## Solution + +```{r, eval=TRUE, purl=TRUE} +ggplot(data = rna, mapping = aes(y = expression_log, x = sample)) + + geom_point(aes(color = time)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +## Boîte à moustaches + +Nous pouvons utiliser des boxplots pour visualiser la distribution des expressions géniques +au sein de chaque échantillon : + +```{r boxplot, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_boxplot() +``` + +En ajoutant des points au boxplot, on peut avoir une meilleure idée du nombre de +mesures et de leur répartition : + +```{r boxplot-with-points, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_jitter(alpha = 0.2, color = "tomato") + + geom_boxplot(alpha = 0) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi + +Notez comment la couche de boîte à moustaches se trouve devant la couche de gigue ? Que devez-vous +modifier dans le code pour placer le boxplot sous les points ? + +::::::::::::::: solution + +## Solution + +Nous devrions inverser l'ordre de ces deux géométries : + +```{r boxplot-with-points2, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_boxplot(alpha = 0) + + geom_jitter(alpha = 0.2, color = "tomato") +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +Vous remarquerez peut-être que les valeurs sur l'axe des x ne sont toujours pas correctement +lisibles. Modifions l'orientation des étiquettes et ajustons-les +verticalement et horizontalement afin qu'elles ne se chevauchent pas. Vous pouvez utiliser un angle de +90 degrés ou expérimenter pour trouver l'angle approprié pour +les étiquettes orientées en diagonale : + +```{r boxplot-xaxis-rotated, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_jitter(alpha = 0.2, color = "tomato") + + geom_boxplot(alpha = 0) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi + +Ajoutez de la couleur aux points de données sur votre boxplot en fonction de la durée +de l'infection (« time »). + +_Indice :_ Vérifiez la classe pour « heure ». Envisagez de changer la classe de +`time` d'entier pour prendre en compte directement dans le mappage ggplot. Pourquoi +cela change-t-il la façon dont R crée le graphique ? + +::::::::::::::: solution + +## Solution + +```{r boxplot-color-time, cache=FALSE, purl=TRUE} +# time as integer +ggplot(data = rna, + mapping = aes(y = expression_log, + x = sample)) + + geom_jitter(alpha = 0.2, aes(color = time)) + + geom_boxplot(alpha = 0) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) + +# time as factor +ggplot(data = rna, + mapping = aes(y = expression_log, + x = sample)) + + geom_jitter(alpha = 0.2, aes(color = as.factor(time))) + + geom_boxplot(alpha = 0) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi + +Les boxplots sont des résumés utiles, mais cachent la _forme_ de la distribution +. Par exemple, si la distribution est bimodale, nous ne la verrions +pas dans un boxplot. Une alternative au boxplot est le tracé en violon +, où la forme (de la densité de points) est dessinée. + +- Remplacez la boîte à moustaches par une intrigue en violon ; voir `geom_violin()`. Remplissez + les violons en fonction du temps avec l'argument `fill`. + +::::::::::::::: solution + +## Solution + +```{r, eval=TRUE, echo=TRUE, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_violin(aes(fill = as.factor(time))) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi + +- Modifiez l'intrigue des violons pour remplir les violons par « sexe ». + +::::::::::::::: solution + +## Solution + +```{r, eval=TRUE, echo=TRUE, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_violin(aes(fill = sex)) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +## Tracés linéaires + +Calculons l'expression moyenne par durée de l'infection pour +les 10 gènes ayant les changements logarithmiques les plus élevés en comparant le temps 8 au +temps 0. Tout d'abord, nous devons sélectionner les gènes et créer un sous-ensemble de `rna` +appelé `sub_rna` contenant les 10 gènes sélectionnés, puis nous devons regrouper +les données et calculer l'expression moyenne des gènes dans chaque groupe: + +```{r, purl=TRUE} +rna_fc <- rna_fc %>% arrange(desc(time_8_vs_0)) + +genes_selected <- rna_fc$gene[1:10] + +sub_rna <- rna %>% + filter(gene %in% genes_selected) + +mean_exp_by_time <- sub_rna %>% + group_by(gene,time) %>% + summarize(mean_exp = mean(expression_log)) + +mean_exp_by_time +``` + +Nous pouvons construire le tracé linéaire avec la durée de l'infection sur l'axe des x +et l'expression moyenne sur l'axe des y : + +```{r first-time-series, purl=TRUE} +ggplot(data = moyenne_exp_by_time, mapping = aes(x = temps, y = moyenne_exp)) + + geom_line() +``` + +Malheureusement, cela ne fonctionne pas car nous avons tracé ensemble les données de tous les gènes +. Nous devons dire à ggplot de tracer une ligne pour chaque gène en +modifiant la fonction esthétique pour inclure `group = gene` : + +```{r time-series-by-gene, purl=TRUE} +ggplot(data = moyenne_exp_by_time, + mapping = aes(x = temps, y = moyenne_exp, groupe = gène)) + + geom_line() +``` + +Nous pourrons distinguer les gènes dans l'intrigue si nous ajoutons des couleurs (l'utilisation de +`color` regroupe également automatiquement les données) : + +```{r time-series-with-colors, purl=TRUE} +ggplot(data = moyenne_exp_by_time, + mapping = aes(x = temps, y = moyenne_exp, couleur = gène)) + + geom_line() +``` + +## Facettage + +`ggplot2` a une technique spéciale appelée _faceting_ qui permet à l'utilisateur +de diviser une parcelle en plusieurs (sous) parcelles en fonction d'un facteur inclus +dans l'ensemble de données. Ces différentes sous-parcelles héritent des mêmes propriétés +(limites des axes, ticks, ...) pour faciliter leur comparaison directe. Nous allons +l'utiliser pour créer un tracé linéaire dans le temps pour chaque gène : + +```{r first-facet, purl=TRUE} +ggplot(data = moyenne_exp_by_time, + mapping = aes(x = temps, y = moyenne_exp)) + geom_line() + + facet_wrap(~ gène) +``` + +Ici, les axes x et y ont la même échelle pour toutes les sous-parcelles. Vous +pouvez changer ce comportement par défaut en modifiant `scales` afin d'autoriser +une échelle libre pour l'axe y : + +```{r first-facet-scales, purl=TRUE} +ggplot(data = moyenne_exp_by_time, + mapping = aes(x = temps, y = moyenne_exp)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") +``` + +Nous aimerions maintenant diviser la ligne dans chaque parcelle selon le sexe des souris. +Pour ce faire, nous devons calculer l'expression moyenne dans le bloc de données +regroupé par « gène », « temps » et « sexe » : + +```{r data-facet-by-gene-and-sex, purl=TRUE} +Mean_exp_by_time_sex <- sub_rna %>% + group_by(gene, time, sex) %>% + summary(mean_exp = Mean(expression_log)) + +Mean_exp_by_time_sex +``` + +Nous pouvons maintenant créer le tracé à facettes en le divisant davantage par sexe en utilisant +`color` (au sein d'un seul tracé) : + +```{r facet-by-gene-and-sex, cache=FALSE, purl=TRUE} +ggplot(data = moyenne_exp_by_time_sex, + mapping = aes(x = temps, y = moyenne_exp, couleur = sexe)) + + geom_line() + + facet_wrap(~ gène, échelles = "free_y") +``` + +Généralement, les tracés sur fond blanc semblent plus lisibles une fois imprimés. Nous +pouvons définir l'arrière-plan en blanc en utilisant la fonction `theme_bw()`. +De plus, nous pouvons supprimer la grille : + +```{r facet-by-gene-and-sex-white-bg, cache=FALSE, purl=TRUE} +ggplot(data = moyenne_exp_by_time_sex, + mapping = aes(x = temps, y = moyenne_exp, couleur = sexe)) + + geom_line() + + facet_wrap(~ gène, échelles = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi + +Utilisez ce que vous venez d'apprendre pour créer un graphique illustrant comment l'expression moyenne +de chaque chromosome change au cours de la durée de l'infection +. + +::::::::::::::: solution + +## Solution + +```{r mean-exp-chromosome-time-series, purl=TRUE} +Mean_exp_by_chromosome <- rna %>% + group_by(chromosome_name, time) %>% + summary(mean_exp = Mean(expression_log)) + +ggplot(data = Mean_exp_by_chromosome, mapping = aes( x = temps, + y = moyenne_exp)) + + geom_line() + + facet_wrap(~ chromosome_name, scales = "free_y") +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +La géométrie `facet_wrap` extrait les tracés dans un nombre arbitraire de +dimensions pour leur permettre de s'adapter proprement à une seule page. On the other hand, +the `facet_grid` geometry allows you to explicitly specify how you want +your plots to be arranged via formula notation (`rows ~ columns`; a `.` +can be used as a placeholder that indicates only one row or column). + +Modifions le graphique précédent pour comparer l'évolution de l'expression génétique moyenne +des hommes et des femmes au fil du temps : + +```{r mean-exp-time-facet-sex-rows, purl=TRUE} +# Une colonne, facette par lignes +ggplot(data = Mean_exp_by_time_sex, + mapping = aes(x = time, y = Mean_exp, color = gene)) + + geom_line() + + facet_grid(sexe ~ .) +``` + +```{r mean-exp-time-facet-sex-columns, purl=TRUE} +# Une ligne, facette par colonne +ggplot(data = Mean_exp_by_time_sex, + mapping = aes(x = time, y = Mean_exp, color = gene)) + + geom_line() + + facet_grid(. ~ sexe) +``` + +## Thèmes `ggplot2` + +En plus de `theme_bw()`, qui change l'arrière-plan de l'intrigue en blanc, +`ggplot2` est livré avec plusieurs autres thèmes qui peuvent être utiles pour +changer rapidement l'apparence de votre visualisation. La liste complète des thèmes est +disponible sur [https://ggplot2.tidyverse.org/reference/ggtheme.html](https://ggplot2.tidyverse.org/reference/ggtheme.html). +`theme_minimal()` et `theme_light()` sont populaires, et `theme_void()` +peut être utile comme point de départ pour créer un nouveau thème créé à la main. + +Le package [ggthemes](https://jrnold.github.io/ggthemes/reference/index.html) +fournit une grande variété d'options (y compris un thème Excel 2003 +). The ggplot2 provides a list of +packages that extend the capabilities of `ggplot2`, including additional +themes. + +## Personnalisation + +Revenons à l'intrigue à facettes de l'expression moyenne par temps et gène, +colorée par sexe. + +Jetez un œil à la feuille de triche , +et réfléchissez aux moyens vous pourriez améliorer l'intrigue. + +Maintenant, nous pouvons changer les noms des axes en quelque chose de plus informatif que +'time' et 'mean\_exp', et ajouter un titre à la figure : + +```{r mean_exp-time-with-right-labels, cache=FALSE, purl=TRUE} +ggplot(data = moyenne_exp_by_time_sex, + mapping = aes(x = temps, y = moyenne_exp, couleur = sexe)) + + geom_line() + + facet_wrap(~ gène, échelles = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + labs(title = "Expression moyenne des gènes selon la durée de l'infection", + x = "Durée de l'infection (en jours)", + y = "Expression moyenne des gènes") +``` + +Les axes ont des noms plus informatifs, mais leur lisibilité peut être +améliorée en augmentant la taille de la police : + +```{r mean_exp-time-with-right-labels-xfont-size, cache=FALSE, purl=TRUE} +ggplot(data = moyenne_exp_by_time_sex, + mapping = aes(x = temps, y = moyenne_exp, couleur = sexe)) + + geom_line() + + facet_wrap(~ gène, échelles = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + labs(title = "Expression moyenne des gènes selon la durée de l'infection", + x = "Durée de l'infection (en jours)", + y = "Expression génétique moyenne") + + theme(text = element_text(size = 16)) +``` + +Notez qu'il est également possible de changer les polices de vos tracés. Si vous +êtes sous Windows, vous devrez peut-être installer le [**`extrafont`** +package](https://cran.r-project.org/web/packages/extrafont /index.html). + +Nous pouvons personnaliser davantage la couleur du texte des axes x et y, la couleur de +la grille, etc. Nous pouvons aussi par exemple déplacer la légende vers le haut en +définissant `legend.position` sur `"top"`. + +```{r mean_exp-time-with-theme, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + labs(title = "Mean gene expression by duration of the infection", + x = "Duration of the infection (in days)", + y = "Mean gene expression") + + theme(text = element_text(size = 16), + axis.text.x = element_text(colour = "royalblue4", size = 12), + axis.text.y = element_text(colour = "royalblue4", size = 12), + panel.grid = element_line(colour="lightsteelblue1"), + legend.position = "top") +``` + +Si vous préférez les modifications que vous avez créées au thème par défaut, vous pouvez +les enregistrer en tant qu'objet pour pouvoir les appliquer facilement à d'autres +tracés que vous pourriez créer. Voici un exemple avec l'histogramme que nous avons +créé précédemment. + +```{r mean_exp-time-with-right-labels-xfont, cache=FALSE, purl=TRUE} +blue_theme <- theme(axis.text.x = element_text(colour = "royalblue4", + size = 12), + axis.text.y = element_text(colour = "royalblue4", + size = 12), + text = element_text(size = 16), + panel.grid = element_line(colour="lightsteelblue1")) + +ggplot(rna, aes(x = expression_log)) + + geom_histogram(bins = 20) + + blue_theme +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi + +Avec toutes ces informations en main, veuillez prendre encore cinq minutes +pour soit améliorer l'un des tracés générés dans cet exercice, soit +créer votre propre graphique. Utilisez la feuille de triche RStudio ggplot2 +pour vous inspirer. Voici quelques idées : + +- Voyez si vous pouvez modifier l’épaisseur des lignes. +- Pouvez-vous trouver un moyen de changer le nom de la légende ? Qu'en est-il de + ses étiquettes ? (indice : recherchez une fonction ggplot commençant par + `scale_`) +- Essayez d'utiliser une palette de couleurs différente ou de spécifier manuellement les couleurs + pour les lignes (voir + [http://www.cookbook-r.com/Graphs/Colors\_(ggplot2)/](https://www.cookbook-r.com/Graphs/Colors_\\(ggplot2\\)/)). + +::::::::::::::: solution + +## Solution + +Par exemple, sur la base de ce tracé : + +```{r, purl=TRUE} +ggplot(data = moyenne_exp_by_time_sex, + mapping = aes(x = temps, y = moyenne_exp, couleur = sexe)) + + geom_line() + + facet_wrap(~ gène, échelles = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) +``` + +Nous pouvons le personnaliser des manières suivantes : + +```{r, purl=TRUE} +# change the thickness of the lines +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line(size=1.5) + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + +# change the name of the legend and the labels +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + scale_color_discrete(name = "Gender", labels = c("F", "M")) + +# using a different color palette +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + scale_color_brewer(name = "Gender", labels = c("F", "M"), palette = "Dark2") + +# manually specifying the colors +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + scale_color_manual(name = "Gender", labels = c("F", "M"), + values = c("royalblue", "deeppink")) + +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::: + +## Composer des intrigues + +Faceting is a great tool for splitting one plot into multiple subplots, +but sometimes you may want to produce a single figure that contains +multiple independent plots, i.e. plots that are based on different +variables or even different data frames. + +Commençons par créer les deux tracés que nous souhaitons disposer l'un à côté de l'autre + : + +Le premier graphique compte le nombre de gènes uniques par chromosome. Nous +devons d'abord réorganiser les niveaux de `chromosome_name` et filtrer les +gènes uniques par chromosome. Nous modifions également l'échelle de l'axe y en une échelle +log10 pour une meilleure lisibilité. + +```{r sub1, purl=TRUE} +arn$chromosome_name <- factor(rna$chromosome_name, + niveaux = c(1:19,"X","Y")) + +count_gene_chromosome <- rna %> % select(chromosome_name, gene) %>% + distinct() %>% ggplot() + + geom_bar(aes(x = chromosome_name), fill = "seagreen", + position = "esquive", stat = "count") + + labs(y = "log10(n gènes)", x = "chromosome") + + scale_y_log10() + +count_gene_chromosome +``` + +Ci-dessous, nous supprimons également complètement la légende en définissant +`legend.position` sur `"none"`. + +```{r sub2, purl=TRUE} +exp_boxplot_sex <- ggplot(rna, aes(y=expression_log, x = as.factor(time), + color=sex)) + + geom_boxplot(alpha = 0) + + labs(y = "Exp moyenne du gène", + x = "time") + theme(legend.position = "none") + +exp_boxplot_sex +``` + +Le package [**patchwork**](https://github.com/thomasp85/patchwork) +fournit une approche élégante pour combiner des figures en utilisant le « + » pour +disposer les figures (généralement latérales). de côté). Plus précisément, le `|` +les dispose explicitement côte à côte et `/` les empile les uns sur les autres +. + +```{r install-patchwork, message=FALSE, eval=FALSE, purl=TRUE} +install.packages("patchwork") +``` + +```{r patchworkplot1, purl=TRUE} +library("patchwork") +count_gene_chromosome + exp_boxplot_sex +## ou count_gene_chromosome | exp_boxplot_sex +``` + +```{r patchwork2, purl=TRUE} +count_gene_chromosome / exp_boxplot_sex +``` + +Nous pouvons combiner un contrôle plus approfondi de la mise en page de la composition finale avec +`plot_layout` pour créer des mises en page plus complexes : + +```{r patchwork3, purl=TRUE} +count_gene_chromosome + exp_boxplot_sex + plot_layout(ncol = 1) +``` + +```{r patchwork4, purl=TRUE} +count_gene_chromosome + + (count_gene_chromosome + exp_boxplot_sex) + + exp_boxplot_sex + + plot_layout(ncol = 1) +``` + +Le dernier tracé peut également être créé à l'aide des compositeurs `|` et `/` : + +```{r patchwork5, purl=TRUE} +count_gene_chromosome / + (count_gene_chromosome | exp_boxplot_sex) / + exp_boxplot_sex +``` + +Apprenez-en plus sur `patchwork` sur sa +[page Web](https://patchwork.data-imaginist.com/) ou dans cette +[vidéo](https://www.youtube. com/watch?v=0m4yywqNPVY). + +Une autre option est le package **`gridExtra`** qui permet de combiner +des ggplots séparés en une seule figure en utilisant `grid.arrange()` : + +```{r install-gridextra, message=FALSE, eval=FALSE, purl=TRUE} +install.packages("gridExtra") +``` + +```{r gridarrange-example, message=FALSE, fig.width=10, purl=TRUE} +library("gridExtra") +grid.arrange(count_gene_chromosome, exp_boxplot_sex, ncol = 2) +``` + +En plus des arguments `ncol` et `nrow`, utilisés pour créer des arrangements +simples, il existe des outils pour [construire des dispositions +plus complexes](https://cran.r-project. org/web/packages/gridExtra/vignettes/arrangeGrob.html). + +## Exporter des tracés + +Après avoir créé votre tracé, vous pouvez l'enregistrer dans un fichier dans votre format +préféré. L'onglet Exporter dans le volet **Plot** de RStudio enregistrera vos tracés +à basse résolution, ce qui ne sera pas accepté par de nombreuses revues et +ne s'adaptera pas bien aux affiches. + +Utilisez plutôt la fonction `ggsave()`, qui vous permet de modifier facilement la dimension +et la résolution de votre tracé en ajustant les arguments +appropriés (`width`, `height` et `dpi` ). + +Assurez-vous d'avoir le dossier `fig_output/` dans votre répertoire de travail. + +```{r ggsave-example, eval=FALSE, purl=TRUE} +my_plot <- ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + labs(title = "Mean gene expression by duration of the infection", + x = "Duration of the infection (in days)", + y = "Mean gene expression") + + guides(color=guide_legend(title="Gender")) + + theme_bw() + + theme(axis.text.x = element_text(colour = "royalblue4", size = 12), + axis.text.y = element_text(colour = "royalblue4", size = 12), + text = element_text(size = 16), + panel.grid = element_line(colour="lightsteelblue1"), + legend.position = "top") +ggsave("fig_output/mean_exp_by_time_sex.png", my_plot, width = 15, + height = 10) + +# This also works for grid.arrange() plots +combo_plot <- grid.arrange(count_gene_chromosome, exp_boxplot_sex, + ncol = 2, widths = c(4, 6)) +ggsave("fig_output/combo_plot_chromosome_sex.png", combo_plot, + width = 10, dpi = 300) +``` + +Remarque : Les paramètres « largeur » et « hauteur » déterminent également la taille de la police +dans le tracé enregistré. + +```{r final-challenge, eval=FALSE, purl=TRUE, echo=FALSE} +### Défi final de tracé : +## Avec toutes ces informations en main, veuillez prendre encore cinq +## minutes pour améliorer l'un des tracés générés dans ce +# # faites de l'exercice ou créez votre propre graphique. Utilisez l'aide-mémoire RStudio +## ggplot2 pour vous inspirer : +## https://raw.githubusercontent.com/rstudio/cheatsheets/main/data-visualization.pdf +``` + +## Autres packages pour la visualisation + +`ggplot2` est un package très puissant qui s'intègre très bien dans notre pipeline _tidy +data_ et _tidy tools_. Il existe d'autres packages de visualisation +dans R qui ne doivent pas être ignorés. + +### Graphiques de base + +Le système graphique par défaut fourni avec R, souvent appelé _base R +graphiques_ est simple et rapide. Il est basé sur le \*modèle de peintre ou de toile +\*, où différentes sorties sont directement superposées les unes sur les +autres (voir figure @ref(fig:paintermodel)). This is a fundamental +difference with `ggplot2` (and with `lattice`, described below), that +returns dedicated objects, that are rendered on screen or in a file, and +that can even be updated. + +```{r paintermodel, fig.width=12, fig.height=4, fig.cap="Successive layers added on top of each other."} +par(mfrow = c(1, 3)) +plot(1:20, main = "Première couche, produite avec plot(1:20)") + +plot(1:20, main = "Une ligne rouge horizontale, ajoutée avec abline(h = 10)") +abline(h = 10, col = "red") + +plot(1:20, main = "Un rectangle , ajouté avec rect(5, 5, 15, 15)") +abline(h = 10, col = "red") +rect(5, 5, 15, 15, lwd = 3 ) +``` + +Une autre différence principale est que la fonction de traçage des graphiques de base essaie de +faire _la bonne_ chose en fonction de leur type d'entrée, c'est-à-dire qu'ils adapteront +leur comportement en fonction de la classe de leur entrée. C'est encore une fois très +différent de ce que nous avons dans `ggplot2`, qui n'accepte que les trames de données +en entrée, et qui nécessite que les tracés soient construits petit à petit. + +```{r plotmethod, fig.width=8, fig.height=8, fig.cap="Plotting boxplots (top) and histograms (bottom) vectors (left) or a matrices (right)."} +par(mfrow = c(2, 2)) +boxplot(rnorm(100), + main = "Boxplot de rnorm(100)") +boxplot(matrix(rnorm( 100), ncol = 10), + main = "Boxplot de la matrice(rnorm(100), ncol = 10)") +hist(rnorm(100)) +hist( matrice(rnorm(100), ncol = 10)) +``` + +L'approche prête à l'emploi dans les graphiques de base peut être très efficace pour +des figures simples et standards, qui peuvent être produites très rapidement avec une +une seule ligne de code et une seule fonction telle que `plot`, ou `hist`, ou +`boxplot`, ... Les valeurs par défaut ne sont cependant pas toujours les plus attractives +et le réglage des figures, surtout lorsqu'elles deviennent plus complexes (par exemple +pour produire des facettes), peut devenir long et fastidieux. + +### Le paquet treillis + +Le package **`lattice`** est similaire à `ggplot2` dans le sens où il utilise +des trames de données en entrée, renvoie des objets graphiques et prend en charge le facettage. +`treillis` cependant n'est pas basé sur la grammaire des graphiques et a une interface plus +alambiquée. + +Une bonne référence pour le package `lattice` est @latticebook. + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Visualisation en R + +:::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/fr/episodes/60-next-steps.Rmd b/locale/fr/episodes/60-next-steps.Rmd new file mode 100644 index 000000000..08d82b85c --- /dev/null +++ b/locale/fr/episodes/60-next-steps.Rmd @@ -0,0 +1,462 @@ +--- +source: Rmd +title: Prochaines étapes +teaching: 45 +exercises: 45 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Présentez le projet Bioconducteur. +- Introduire la notion de conteneurs de données. +- Donnez un aperçu du `SummarizedExperiment`, largement utilisé dans les analyses + omiques. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- Qu'est-ce qu'une « expérience résumée » ? +- Qu’est-ce qu’un bioconducteur ? + +:::::::::::::::::::::::::::::::::::::::::::::::: + +## Prochaines étapes + +```{r, echo=FALSE, message=FALSE} +bibliothèque("tidyverse") +``` + +Les données en bioinformatique sont souvent complexes. Pour résoudre ce problème, les développeurs +définissent des conteneurs de données spécialisés (appelés classes) qui +correspondent aux propriétés des données qu'ils doivent gérer. + +Cet aspect est au cœur du projet **Bioconductor**[^Bioconductor] +qui utilise la même **infrastructure de données de base** dans tous les packages. Ce +a certainement contribué au succès de Bioconductor. Il est conseillé aux développeurs du package Bioconductor +d'utiliser l'infrastructure existante pour +assurer la cohérence, l'interopérabilité et la stabilité du projet dans son ensemble +. + +[^Bioconductor]: Le [Bioconductor](https://www.bioconductor.org) a été + initié par Robert Gentleman, l'un des deux créateurs du langage R + . Bioconductor fournit des outils dédiés à l'analyse des données omiques + . Bioconductor utilise le langage de programmation statistique R + et est open source et développement ouvert. + +Pour illustrer un tel conteneur de données omiques, nous présenterons la classe +`SummarizedExperiment`. + +## Expérience résumée + +La figure ci-dessous représente l’anatomie de la classe SummarizedExperiment. + +```{r SE, echo=FALSE, out.width="80%"} +knitr::include_graphics("https://uclouvain-cbio.github.io/WSBIM1322/figs/SE.svg") +``` + +Les objets de la classe SummarizedExperiment contiennent : + +- **Un (ou plusieurs) test(s)** contenant les données omiques quantitatives + (données d'expression), stockées sous forme d'objet de type matriciel. Caractéristiques (gènes, + transcrits, protéines, ...) sont définis le long des lignes, et les échantillons + le long des colonnes. + +- Un emplacement **exemple de métadonnées** contenant des exemples de covariables, stocké sous forme de trame de données + . Les lignes de ce tableau représentent des échantillons (les lignes correspondent exactement aux colonnes + des données d'expression). + +- Un emplacement de **métadonnées de fonctionnalité** contenant des covariables de fonctionnalité, stockées sous forme de + une trame de données. Les lignes de ce bloc de données correspondent exactement aux lignes des données d'expression + . + +La nature coordonnée du `SummarizedExperiment` garantit que +lors de la manipulation des données, les dimensions des différents emplacements seront toujours +(c'est-à-dire les colonnes des données d'expression puis les lignes de +les exemples de métadonnées, ainsi que les lignes des données d'expression et les +métadonnées des fonctionnalités) lors de la manipulation des données. Par exemple, si nous devions +exclure un échantillon du test, il serait automatiquement supprimé +des métadonnées de l’échantillon au cours de la même opération. + +Les emplacements de métadonnées peuvent développer des co-variables supplémentaires +(colonnes) sans affecter les autres structures. + +### Création d'une expérience résumée + +Afin de créer un `SummarizedExperiment`, nous allons créer les +composants individuels, c'est-à-dire la matrice de comptage, l'échantillon et le gène +métadonnées à partir de fichiers csv. C'est généralement ainsi que les données RNA-Seq sont +fournies (après le traitement des données brutes). + +```{r, echo=FALSE, message=FALSE} +rna <- read_csv("data/rnaseq.csv") + +## count matrix +counts <- rna %>% + select(gene, sample, expression) %>% + pivot_wider(names_from = sample, + values_from = expression) + +## convert to matrix and set row names +count_matrix <- counts %>% select(-gene) %>% as.matrix() +rownames(count_matrix) <- counts$gene + +## sample annotation +sample_metadata <- rna %>% + select(sample, organism, age, sex, infection, strain, time, tissue, mouse) + +## remove redundancy +sample_metadata <- unique(sample_metadata) + +## gene annotation +gene_metadata <- rna %>% + select(gene, ENTREZID, product, ensembl_gene_id, external_synonym, + chromosome_name, gene_biotype, phenotype_description, + hsapiens_homolog_associated_gene_name) + +# remove redundancy +gene_metadata <- unique(gene_metadata) + +## write to csv +write.csv(count_matrix, file = "data/count_matrix.csv") +write.csv(gene_metadata, file = "data/gene_metadata.csv", row.names = FALSE) +write.csv(sample_metadata, file = "data/sample_metadata.csv", row.names = FALSE) +``` + +- **Une matrice d'expression** : nous chargeons la matrice de comptage, en spécifiant que + les premières colonnes contiennent des noms de lignes/gènes, et convertissons le + `data.frame` en une `matrice`. Vous pouvez le télécharger + [ici](https://carpentries-incubator.github.io/bioc-intro/data/count_matrix.csv). + +```{r} +count_matrix <- read.csv("data/count_matrix.csv", + row.names = 1) %>% + as.matrix() + +count_matrix[1:5, ] +dim(count_matrix) +``` + +- **Un tableau décrivant les échantillons**, disponible + [ici](https://carpentries-incubator.github.io/bioc-intro/data/sample_metadata.csv). + +```{r} +sample_metadata <- read.csv("data/sample_metadata.csv") +sample_metadata +dim(sample_metadata) +``` + +- **Un tableau décrivant les gènes**, disponible + [ici](https://carpentries-incubator.github.io/bioc-intro/data/gene_metadata.csv). + +```{r} +gene_metadata <- read.csv("data/gene_metadata.csv") +gene_metadata[1:10, 1:4] +dim(gene_metadata) +``` + +Nous allons créer un `SummarizedExperiment` à partir de ces tables : + +- La matrice de comptage qui sera utilisée comme **`essai`** + +- Le tableau décrivant les échantillons sera utilisé comme emplacement de métadonnées \*\*sample + \*\* + +- Le tableau décrivant les gènes sera utilisé comme emplacement de métadonnées \*\*features + \*\* + +Pour ce faire, nous pouvons assembler les différentes parties à l'aide du constructeur +`SummarizedExperiment` : + +```{r, message=FALSE, warning=FALSE} +## BiocManager::install("SummarizedExperiment") +bibliothèque("SummarizedExperiment") +``` + +Tout d’abord, nous nous assurons que les échantillons sont dans le même ordre dans la matrice de comptage +et l’annotation d’échantillon, et il en va de même pour les gènes dans +la matrice de comptage et l’annotation des gènes. + +```{r} +stopifnot(rownames(count_matrix) == gene_metadata$gene) +stopifnot(colnames(count_matrix) == sample_metadata$sample) +``` + +```{r} +se <- SummarizedExperiment(assays = list(counts = count_matrix), + colData = sample_metadata, + rowData = gene_metadata) +se +``` + +### La sauvegarde des données + +L'export de données vers un tableur, comme nous l'avons fait dans un épisode précédent, présente +plusieurs limitations, comme celles décrites dans le premier chapitre +(éventuelles incohérences avec `,` et `.` pour les séparateurs décimaux et +manque de définitions de types de variables). De plus, l'exportation de données vers une feuille de calcul +n'est pertinente que pour les données rectangulaires telles que les dataframes +et les matrices. + +Une manière plus générale de sauvegarder des données, spécifique à R et dont le fonctionnement est +garanti sur n'importe quel système d'exploitation, consiste à utiliser la fonction `saveRDS` +. L'enregistrement d'objets comme celui-ci générera une représentation binaire +sur le disque (en utilisant l'extension de fichier `rds` ici), qui +peut être rechargée dans R à l'aide de la fonction `readRDS`. + +```{r, eval=FALSE} +saveRDS(se, file = "data_output/se.rds") +rm(se) +se <- readRDS("data_output/se.rds") +head(se) +``` + +Pour conclure, lorsqu'il s'agit de sauvegarder des données de R qui seront chargées +à nouveau dans R, la sauvegarde et le chargement avec `saveRDS` et `readRDS` sont l'approche +préférée. Si les données tabulaires doivent être partagées avec quelqu'un +qui n'utilise pas R, alors l'exportation vers une feuille de calcul textuelle est une +bonne alternative. + +En utilisant cette structure de données, nous pouvons accéder à la matrice d'expression avec +la fonction `assay` : + +```{r} +head(essai(se)) +dim(essai(se)) +``` + +Nous pouvons accéder aux exemples de métadonnées à l'aide de la fonction `colData` : + +```{r} +colData(se) +dim(colData(se)) +``` + +Nous pouvons également accéder aux métadonnées des fonctionnalités à l'aide de la fonction `rowData` : + +```{r} +head(rowData(se)) +dim(rowData(se)) +``` + +### Sous-ensemble d'une expérience résumée + +SummarizedExperiment peut être un sous-ensemble comme avec des trames de données, avec des chiffres +ou avec des caractères logiques. + +Ci-dessous, nous créons une nouvelle instance de la classe SummarizedExperiment qui +contient uniquement les 5 premières fonctionnalités pour les 3 premiers échantillons. + +```{r} +se1 <- se[1:5, 1:3] +se1 +``` + +```{r} +colData(se1) +rowData(se1) +``` + +Nous pouvons également utiliser la fonction `colData()` pour créer un sous-ensemble sur quelque chose de +les exemples de métadonnées ou la fonction `rowData()` pour créer un sous-ensemble sur quelque chose à partir des métadonnées de fonctionnalité +. Par exemple, nous ne conservons ici que les miARN et les échantillons non +infectés : + +```{r} +se1 <- se[rowData(se)$gene_biotype == "miRNA", + colData(se)$infection == "NonInfected"] +se1 +assay(se1) +colData(se1) +rowData(se1) +``` + + + + + + + + + + + + + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi + +Extraire les niveaux d'expression génique des 3 premiers gènes dans les échantillons +au temps 0 et au temps 8. + +::::::::::::::: solution + +## Solution + +```{r, purl=FALSE} +assay(se)[1:3, colData(se)$time != 4] + +# Equivalent to +assay(se)[1:3, colData(se)$time == 0 | colData(se)$time == 8] +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Défi + +Vérifiez que vous obtenez les mêmes valeurs en utilisant la longue table `rna`. + +::::::::::::::: solution + +## Solution + +```{r, purl=FALSE} +arn |> + filtre(gène %in% c("Asl", "Apod", "Cyd2d22")) |> + filtre(temps != 4) |> select(expression ) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +Le long tableau et le `SummarizedExperiment` contiennent les mêmes informations +, mais sont simplement structurés différemment. Chaque approche a ses +propres avantages : la première convient bien aux packages `tidyverse`, +tandis que la seconde est la structure préférée pour de nombreuses étapes de bioinformatique et +de traitement statistique. Par exemple, une analyse typique d'ARN-Seq utilisant +le package `DESeq2`. + +#### Ajouter des variables aux métadonnées + +Nous pouvons également ajouter des informations aux métadonnées. +Supposons que vous souhaitiez ajouter le centre où les échantillons ont été collectés... + +```{r} +colData(se)$center <- rep("Université de l'Illinois", nrow(colData(se))) +colData(se) +``` + +Cela illustre que les emplacements de métadonnées peuvent croître indéfiniment sans +affecter les autres structures ! + +### TidyRésuméExpérience + +Vous vous demandez peut-être si pouvons-nous utiliser les commandes Tidyverse pour interagir avec les objets +`SummarizedExperiment` ? La réponse est oui, nous pouvons le faire avec le package +`tidySummarizedExperiment`. + +Rappelez-vous à quoi ressemble notre objet SummarizedExperiment : + +```{r, message=FALSE} +se +``` + +Chargez `tidySummarizedExperiment` puis jetez à nouveau un œil à l'objet se +. + +```{r, message=FALSE} +#BiocManager::install("tidySummarizedExperiment") +library("tidySummarizedExperiment") + +se +``` + +Il s'agit toujours d'un objet `SummarizedExperiment`, il conserve donc la structure efficace +, mais nous pouvons maintenant le voir comme un tibble. Notez la première ligne de +la sortie dit ceci, c'est une abstraction `SummarizedExperiment`\-`tibble` +. Nous pouvons également voir dans la deuxième ligne de la sortie le nombre +de transcriptions et d'échantillons. + +Si nous voulons revenir à la vue standard `SummarizedExperiment`, nous +pouvons le faire. + +```{r} +options("restore_SummarizedExperiment_show" = TRUE) +se +``` + +Mais ici, nous utilisons la vue tibble. + +```{r} +options("restore_SummarizedExperiment_show" = FALSE) +se +``` + +Nous pouvons maintenant utiliser les commandes Tidyverse pour interagir avec l'objet +`SummarizedExperiment`. + +Nous pouvons utiliser `filter` pour filtrer les lignes en utilisant une condition, par exemple pour afficher +toutes les lignes pour un échantillon. + +```{r} +se %>% filtre(.sample == "GSM2545336") +``` + +Nous pouvons utiliser « select » pour spécifier les colonnes que nous voulons afficher. + +```{r} +se %>% sélectionner (.sample) +``` + +Nous pouvons utiliser `mutate` pour ajouter des informations sur les métadonnées. + +```{r} +se %>% muter(center = "Université de Heidelberg") +``` + +Nous pouvons également combiner des commandes avec le tube Tidyverse `%>%`. Pour l'exemple de +, nous pourrions combiner `group_by` et `summarise` pour obtenir le nombre total de +pour chaque échantillon. + +```{r} +se %>% + group_by(.sample) %>% + summarise(total_counts=sum(counts)) +``` + +Nous pouvons traiter l'objet SummarizedExperiment bien rangé comme un tibble normal +pour le traçage. + +Ici, nous traçons la distribution des comptes par échantillon. + +```{r tidySE-plot} +se %>% + ggplot(aes(counts + 1, group=.sample, color=infection)) + + geom_density() + + scale_x_log10() + + theme_bw() +``` + +Pour plus d'informations sur TidySummarizedExperiment, consultez le site Web du package[ici](https://stemangiola.github.io/tidySummarizedExperiment/). + +**Message à retenir** + +- `SummarizedExperiment` représente un moyen efficace de stocker et + de gérer les données omiques. + +- Ils sont utilisés dans de nombreux packages Bioconductor. + +Si vous suivez la prochaine formation axée sur l'analyse de séquençage d'ARN, +vous apprendrez à utiliser le package Bioconductor `DESeq2` pour faire des +analyses d'expression différentielle. L'ensemble de l'analyse du package `DESeq2` +est géré dans un `SummarizedExperiment`. + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Bioconductor est un projet fournissant un support et des packages pour la + compréhension de données biologiques à haut débit. +- Un `SummarizedExperiment` est un type d'objet utile pour stocker et + gérer des données omiques à haut débit. + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/fr/index.md b/locale/fr/index.md new file mode 100644 index 000000000..f6e3116fd --- /dev/null +++ b/locale/fr/index.md @@ -0,0 +1,18 @@ +--- +permalink: index.html +site: sandpaper::sandpaper_site +--- + +## About this course + +:::::::::::::::::::::::::::::::::::::::::: prereq + +## Prerequisites + +- Familiarity with tabular data and spreadsheets. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + + + + diff --git a/locale/fr/instructors/instructor-notes.md b/locale/fr/instructors/instructor-notes.md new file mode 100644 index 000000000..cec65daca --- /dev/null +++ b/locale/fr/instructors/instructor-notes.md @@ -0,0 +1,9 @@ +--- +title: Instructor Notes +--- + +FIXME + + + + diff --git a/locale/fr/learners/discuss.md b/locale/fr/learners/discuss.md new file mode 100644 index 000000000..515e3baf1 --- /dev/null +++ b/locale/fr/learners/discuss.md @@ -0,0 +1,9 @@ +--- +title: Discussion +--- + +FIXME + + + + diff --git a/locale/fr/learners/reference.md b/locale/fr/learners/reference.md new file mode 100644 index 000000000..3466d35cf --- /dev/null +++ b/locale/fr/learners/reference.md @@ -0,0 +1,11 @@ +--- +{} +--- + +## Glossary + +FIXME + + + + diff --git a/locale/fr/learners/setup.md b/locale/fr/learners/setup.md new file mode 100644 index 000000000..ee72394a9 --- /dev/null +++ b/locale/fr/learners/setup.md @@ -0,0 +1,151 @@ +--- +title: Setup +--- + +- Veuillez vous assurer d'avoir accès à un tableur, tel que LibreOffice, Microsoft Excel ou Google Sheets. + +- Installez R, RStudio et les packages (voir ci-dessous). + +### R et RStudio + +- R et RStudio sont des programmes a télécharger separemment et demandent des installations distincts. R est l'environnement de calcul statistique sous-jacent, mais utiliser R seul peut être pénible. RStudio est un environnement de développement graphique intégré + (IDE) qui rend l'utilisation de R beaucoup plus simple et plus interactive. Vous avez besoin d' installer R avant d'installer RStudio. Après avoir installé les deux programmes, vous devrez installer des paquets R spécifiques depuis + RStudio. Suivez les instructions ci-dessous pour votre système d'exploitation, + puis suivez les instructions pour installer des paquets. + +### You are running Windows + +
+ +::::::::::::::: solution + +## Si vous avez déjà installé R et RStudio + +- Ouvrez RStudio et cliquez sur « Aide » > « Rechercher les mises à jour ». Si une nouvelle version est + disponible, quittez RStudio et téléchargez la dernière version de RStudio. + +- Pour vérifier quelle version de R vous utilisez, démarrez RStudio et la première chose + qui apparaît dans la console indique la version de R que vous + exécutez. Alternativement, vous pouvez taper `sessionInfo()`, qui affichera également + quelle version de R est installée. Allez sur + le [site Web du CRAN](https://cran.r-project.org/bin/windows/base/) et vérifiez + si une version plus récente est disponible. Si c'est le cas, veuillez le télécharger et l'installer. Vous pouvez [consulter ici](https://cran.r-project.org/bin/windows/base/rw-FAQ.html#How-do-I-UNinstall-R_003f) pour + plus d'informations sur la façon de supprimer les anciennes versions de votre système si vous souhaitez le faire. + +- Suivez les étapes décrites dans les instructions [pour tout le monde](#pour-tout-le-monde) en bas de cette page. + +::::::::::::::::::::::::: + +::::::::::::::: solution + +## If you don't have R and RStudio installed + +- Download R from + the [CRAN website](https://cran.r-project.org/bin/windows/base/release.htm). + +- Run the `.exe` file that was just downloaded + +- Go to the [RStudio download page](https://www.rstudio.com/products/rstudio/download/#download) + +- Under _All Installers_ select **RStudio xxxx.yy.zz-uuu.exe - Windows 10/11** (where x, y, z, and u represent version numbers) + +- Double click the file to install it + +- Once it's installed, open RStudio to make sure it works and you don't get any + error messages + +- Follow the steps in the instructions [for everyone](#for-everyone) at the + bottom of this page. + +::::::::::::::::::::::::: + +### You are running macOS + +
+ +::::::::::::::: solution + +## If you already have R and RStudio installed + +- Open RStudio, and click on "Help" > "Check for updates". If a new version is + available, quit RStudio, and download the latest version for RStudio. + +- To check the version of R you are using, start RStudio and the first thing + that appears on the terminal indicates the version of R you are running. Alternatively, you can type `sessionInfo()`, which will + also display which version of R you are running. Go on + the [CRAN website](https://cran.r-project.org/bin/macosx/) and check + whether a more recent version is available. If so, please download and install + it. + +- Follow the steps in the instructions [for everyone](#for-everyone) at the + bottom of this page. + +::::::::::::::::::::::::: + +::::::::::::::: solution + +## If you don't have R and RStudio installed + +- Download R from + the [CRAN website](https://cran.r-project.org/bin/macosx/). + +- Select the `.pkg` file for the latest R version + +- Double click on the downloaded file to install R + +- It is also a good idea to install [XQuartz](https://www.xquartz.org/) (needed + by some packages) + +- Go to the [RStudio download page](https://www.rstudio.com/products/rstudio/download/#download) + +- Under _All Installers_ select **RStudio xxxx.yy.zz-uuu.dmg - macOS 10.15+** (where x, y, z, and u represent version numbers) + +- Double click the file to install RStudio + +- Once it's installed, open RStudio to make sure it works and you don't get any + error messages. + +- Follow the steps in the instructions [for everyone](#for-everyone) at the + bottom of this page. + +::::::::::::::::::::::::: + +### You are running Linux + +
+ +::::::::::::::: solution + +## Install R using your package manager and RStudio + +- Follow the instructions for your distribution + from [CRAN](https://cloud.r-project.org/bin/linux), they provide information + to get the most recent version of R for common distributions. For most + distributions, you could use your package manager (e.g., for Debian/Ubuntu run + `sudo apt-get install r-base`, and for Fedora `sudo yum install R`), but we + don't recommend this approach as the versions provided by this are + usually out of date. In any case, make sure you have at least R 4.2.0. +- Go to the RStudio download + page +- Under _All Installers_ select the version that matches your distribution, and + install it with your preferred method (e.g., with Debian/Ubuntu `sudo dpkg -i rstudio-xxxx.yy.zz-uuu-amd64.deb` at the terminal). +- Once it's installed, open RStudio to make sure it works and you don't get any + error messages. +- Follow the steps in the [instructions for everyone](#for-everyone) + +::::::::::::::::::::::::: + +### For everyone + +After installing R and RStudio, you need to install a couple of +packages that will be used during the workshop. We will also learn +about package installation during the course to explain the following +commands. For now, simply follow the instructions below: + +- Start RStudio by double-clicking the icon and then type: + +```r +install.packages(c("BiocManager", "remotes")) +BiocManager::install(c("tidyverse", "SummarizedExperiment", "hexbin", + "patchwork", "gridExtra", "lubridate")) +``` diff --git a/locale/fr/profiles/learner-profiles.md b/locale/fr/profiles/learner-profiles.md new file mode 100644 index 000000000..75b2c5cad --- /dev/null +++ b/locale/fr/profiles/learner-profiles.md @@ -0,0 +1,5 @@ +--- +title: FIXME +--- + +This is a placeholder file. Please add content here. diff --git a/locale/ja/CODE_OF_CONDUCT.md b/locale/ja/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..a820b8df5 --- /dev/null +++ b/locale/ja/CODE_OF_CONDUCT.md @@ -0,0 +1,12 @@ +--- +title: Contributor Code of Conduct +--- + +As contributors and maintainers of this project, +we pledge to follow the [The Carpentries Code of Conduct][coc]. + +Instances of abusive, harassing, or otherwise unacceptable behavior +may be reported by following our [reporting guidelines][coc-reporting]. + +[coc-reporting]: https://docs.carpentries.org/topic_folders/policies/incident-reporting.html +[coc]: https://docs.carpentries.org/topic_folders/policies/code-of-conduct.html diff --git a/locale/ja/CONTRIBUTING.md b/locale/ja/CONTRIBUTING.md new file mode 100644 index 000000000..5dfea562d --- /dev/null +++ b/locale/ja/CONTRIBUTING.md @@ -0,0 +1,151 @@ +# Contributing + +[Software Carpentry][swc-site] and [Data Carpentry][dc-site] are open source projects, +and we welcome contributions of all kinds: +new lessons, +fixes to existing material, +bug reports, +and reviews of proposed changes are all welcome. + +## Contributor Agreement + +By contributing, +you agree that we may redistribute your work under [our license](LICENSE.md). +In exchange, +we will address your issues and/or assess your change proposal as promptly as we can, +and help you become a member of our community. +Everyone involved in [Software Carpentry][swc-site] and [Data Carpentry][dc-site] +agrees to abide by our [code of conduct](CONDUCT.md). + +## How to Contribute + +The easiest way to get started is to file an issue +to tell us about a spelling mistake, +some awkward wording, +or a factual error. +This is a good way to introduce yourself +and to meet some of our community members. + +1. If you do not have a [GitHub][github] account, + you can [send us comments by email][contact]. + However, + we will be able to respond more quickly if you use one of the other methods described below. + +2. If you have a [GitHub][github] account, + or are willing to [create one][github-join], + but do not know how to use Git, + you can report problems or suggest improvements by [creating an issue][issues]. + This allows us to assign the item to someone + and to respond to it in a threaded discussion. + +3. If you are comfortable with Git, + and would like to add or change material, + you can submit a pull request (PR). + Instructions for doing this are [included below](#using-github). + +## Where to Contribute + +1. If you wish to change this lesson, + please work in , + which can be viewed at . + +2. If you wish to change the example lesson, + please work in , + which documents the format of our lessons + and can be viewed at . + +3. If you wish to change the template used for workshop websites, + please work in . + The home page of that repository explains how to set up workshop websites, + while the extra pages in + provide more background on our design choices. + +4. If you wish to change CSS style files, tools, + or HTML boilerplate for lessons or workshops stored in `_includes` or `_layouts`, + please work in . + +## What to Contribute + +There are many ways to contribute, +from writing new exercises and improving existing ones +to updating or filling in the documentation +and submitting [bug reports][issues] +about things that don't work, aren't clear, or are missing. +If you are looking for ideas, +please see [the list of issues for this repository][issues], +or the issues for [Data Carpentry][dc-issues] +and [Software Carpentry][swc-issues] projects. + +Comments on issues and reviews of pull requests are just as welcome: +we are smarter together than we are on our own. +Reviews from novices and newcomers are particularly valuable: +it's easy for people who have been using these lessons for a while +to forget how impenetrable some of this material can be, +so fresh eyes are always welcome. + +## What _Not_ to Contribute + +Our lessons already contain more material than we can cover in a typical workshop, +so we are usually _not_ looking for more concepts or tools to add to them. +As a rule, +if you want to introduce a new idea, +you must (a) estimate how long it will take to teach +and (b) explain what you would take out to make room for it. +The first encourages contributors to be honest about requirements; +the second, to think hard about priorities. + +We are also not looking for exercises or other material that only run on one platform. +Our workshops typically contain a mixture of Windows, macOS, and Linux users; +in order to be usable, +our lessons must run equally well on all three. + +## Using GitHub + +If you choose to contribute via GitHub, +you may want to look at +[How to Contribute to an Open Source Project on GitHub][how-contribute]. +In brief: + +1. The published copy of the lesson is in the `gh-pages` branch of the repository + (so that GitHub will regenerate it automatically). + Please create all branches from that, + and merge the [master repository][repo]'s `gh-pages` branch into your `gh-pages` branch + before starting work. + Please do _not_ work directly in your `gh-pages` branch, + since that will make it difficult for you to work on other contributions. + +2. We use [GitHub flow][github-flow] to manage changes: + 1. Create a new branch in your desktop copy of this repository for each significant change. + 2. Commit the change in that branch. + 3. Push that branch to your fork of this repository on GitHub. + 4. Submit a pull request from that branch to the [master repository][repo]. + 5. If you receive feedback, + make changes on your desktop and push to your branch on GitHub: + the pull request will update automatically. + +Each lesson has two maintainers who review issues and pull requests +or encourage others to do so. +The maintainers are community volunteers, +and have final say over what gets merged into the lesson. + +## Other Resources + +General discussion of [Software Carpentry][swc-site] and [Data Carpentry][dc-site] +happens on the [discussion mailing list][discuss-list], +which everyone is welcome to join. +You can also [reach us by email][contact]. + +[contact]: mailto:admin@software-carpentry.org +[dc-issues]: https://github.com/issues?q=user%3Adatacarpentry +[dc-lessons]: http://datacarpentry.org/lessons/ +[dc-site]: http://datacarpentry.org/ +[discuss-list]: http://lists.software-carpentry.org/listinfo/discuss +[github]: http://github.com +[github-flow]: https://guides.github.com/introduction/flow/ +[github-join]: https://github.com/join +[how-contribute]: https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github +[issues]: https://github.com/swcarpentry/shell-novice/issues/ +[repo]: https://github.com/swcarpentry/shell-novice/ +[swc-issues]: https://github.com/issues?q=user%3Aswcarpentry +[swc-lessons]: http://software-carpentry.org/lessons/ +[swc-site]: http://software-carpentry.org/ diff --git a/locale/ja/LICENSE.md b/locale/ja/LICENSE.md new file mode 100644 index 000000000..696cc3ae1 --- /dev/null +++ b/locale/ja/LICENSE.md @@ -0,0 +1,82 @@ +--- +title: Licenses +--- + +## Instructional Material + +All Software Carpentry, Data Carpentry, and Library Carpentry instructional material is +made available under the [Creative Commons Attribution +license][cc-by-human]. The following is a human-readable summary of +(and not a substitute for) the [full legal text of the CC BY 4.0 +license][cc-by-legal]. + +You are free: + +- to **Share**---copy and redistribute the material in any medium or format +- to **Adapt**---remix, transform, and build upon the material + +for any purpose, even commercially. + +The licensor cannot revoke these freedoms as long as you follow the +license terms. + +Under the following terms: + +- **Attribution**---You must give appropriate credit (mentioning that + your work is derived from work that is Copyright © Software + Carpentry and, where practical, linking to + http\://software-carpentry.org/), provide a [link to the + license][cc-by-human], and indicate if changes were made. You may do + so in any reasonable manner, but not in any way that suggests the + licensor endorses you or your use. + +**No additional restrictions**---You may not apply legal terms or +technological measures that legally restrict others from doing +anything the license permits. With the understanding that: + +Notices: + +- You do not have to comply with the license for elements of the + material in the public domain or where your use is permitted by an + applicable exception or limitation. +- No warranties are given. The license may not give you all of the + permissions necessary for your intended use. For example, other + rights such as publicity, privacy, or moral rights may limit how you + use the material. + +## Software + +Except where otherwise noted, the example programs and other software +provided by Software Carpentry and Data Carpentry are made available under the +[OSI][osi]-approved +[MIT license][mit-license]. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +## Trademark + +"Software Carpentry" and "Data Carpentry" and their respective logos +are registered trademarks of [Community Initiatives][ci]. + +[cc-by-human]: https://creativecommons.org/licenses/by/4.0/ +[cc-by-legal]: https://creativecommons.org/licenses/by/4.0/legalcode +[mit-license]: https://opensource.org/licenses/mit-license.html +[ci]: http://communityin.org/ +[osi]: https://opensource.org diff --git a/locale/ja/README.md b/locale/ja/README.md new file mode 100644 index 000000000..fec09d0f3 --- /dev/null +++ b/locale/ja/README.md @@ -0,0 +1,75 @@ +# Introduction to genomic data analysis with R and Bioconductor + +[![Create a Slack Account with us](https://img.shields.io/badge/Create_Slack_Account-The_Carpentries-071159.svg)](https://swc-slack-invite.herokuapp.com/) + +## Contributing + +We welcome all contributions to improve the lesson! Maintainers will +do their best to help you if you have any questions, concerns, or +experience any difficulties along the way. + +We'd like to ask you to familiarize yourself with our Contribution +Guide and have a look at the [more detailed +guidelines][lesson-example] on proper formatting, ways to render the +lesson locally, and even how to write new episodes. + +Please see the current list of [issues][FIXME] for ideas for +contributing to this repository. For making your contribution, we use +the GitHub flow, which is nicely explained in the chapter +Contributing to a +Project +in Pro Git by Scott Chacon. + +Look for the tag +![good\_first\_issue](https://img.shields.io/badge/-good%20first%20issue-gold.svg). This +indicates that the maintainers will welcome a pull request fixing this +issue. + +## Useful links + +- If you're going to be developing lesson material for the first time + according to our design principles, consider reading the + [Carpentries Curriculum Development Handbook][cdh] +- Consult the [Lesson Example][lesson-example] website to find out more about + working with the lesson template + +## Lesson team + +This lesson has been developed and is current maintained by + +- Laurent Gatto (maintainer) +- Charlotte Soneson +- Jenny Drnevich +- Robert Castelo +- Kevin Rue-Albert + +We would also like to acknowledge the contributions of: + +- Oliver Crook, Sarah Kaspar, Nick Hirschmueller, Lisa Breckels and Maria Doyle for their contributions during the Bioconductor introduction workshop in Heidelberg, as part of EuroBioc2021 |> 2022. +- Axelle Loriot, Marco Chiapelle, Manon Martin and Toby Hodges for various contributions and discussions. +- lmsimp, alorot, manonmartin, mchiapello, stavares843, JennyZadeh, csdaw, ninja-1337, fursham-h, lagerratrobe, fmichonneau, federicomarini, tobyhodges for pull requests. + +If we have contributed but we missed you, apologies, and feel free to add yourself with a PR. + +## Authors + +A list of contributors to the lesson can be found in [AUTHORS](AUTHORS) + +## Citation + +To cite this lesson, please consult with [CITATION](CITATION) + +[lesson-example]: https://carpentries.github.io/lesson-example +[cdh]: https://cdh.carpentries.org + +## Testing locally + +To test locally, run the following in the lessons directory: + +```r +sandpaper::serve() +``` + +For more details, see the [workbench installation +instructions](https://carpentries.github.io/workbench/#installation]. + diff --git a/locale/ja/config.yaml b/locale/ja/config.yaml new file mode 100644 index 000000000..204cb59c5 --- /dev/null +++ b/locale/ja/config.yaml @@ -0,0 +1,61 @@ +#------------------------------------------------------------ +#Values for this lesson. +#------------------------------------------------------------ +#Which carpentry is this (swc, dc, lc, or cp)? +#swc: Software Carpentry +#dc: Data Carpentry +#lc: Library Carpentry +#cp: Carpentries (to use for instructor training for instance) +#incubator: The Carpentries Incubator +carpentry: 'incubator' +#Overall title for pages. +title: 'Introduction to data analysis with R and Bioconductor' +#Date the lesson was created (YYYY-MM-DD, this is empty by default) +created: '2020-09-14' +#Comma-separated list of keywords for the lesson +keywords: 'software, data, lesson, The Carpentries' +#Life cycle stage of the lesson +#possible values: pre-alpha, alpha, beta, stable +life_cycle: 'stable' +#License of the lesson +license: 'CC-BY 4.0' +#Link to the source repository for this lesson +source: 'https://github.com/carpentries-incubator/bioc-intro' +#Default branch of your lesson +branch: 'main' +#Who to contact if there are any issues +contact: 'laurent.gatto@uclouvain.be' +#Navigation ------------------------------------------------ +#Use the following menu items to specify the order of +#individual pages in each dropdown section. Leave blank to +#include all pages in the folder. +#Example ------------- +#episodes: +#- introduction.md +#- first-steps.md +#learners: +#- setup.md +#instructors: +#- instructor-notes.md +#profiles: +#- one-learner.md +#- another-learner.md +#Order of episodes in your lesson +episodes: + - 10-data-organisation.Rmd + - 20-r-rstudio.Rmd + - 23-starting-with-r.Rmd + - 25-starting-with-data.Rmd + - 30-dplyr.Rmd + - 40-visualization.Rmd + - 60-next-steps.Rmd +#Information for Learners +learners: +#Information for Instructors +instructors: +#Learner Profiles +profiles: +#Customisation --------------------------------------------- +#This space below is where custom yaml items (e.g. pinning +#sandpaper and varnish versions) should live +url: 'https://carpentries-incubator.github.io/bioc-intro' diff --git a/locale/ja/episodes/10-data-organisation.Rmd b/locale/ja/episodes/10-data-organisation.Rmd new file mode 100644 index 000000000..31aa512c5 --- /dev/null +++ b/locale/ja/episodes/10-data-organisation.Rmd @@ -0,0 +1,821 @@ +--- +source: RMD +title: スプレッドシートを使用したデータ整理 +teaching: 30 +exercises: 30 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- スプレッドシートとその長所と短所について学びます。 +- データを効果的に使用するには、スプレッドシート内のデータをどのようにフォーマットすればよいでしょうか? +- 一般的なスプレッドシートのエラーとその修正方法について説明します。 +- きちんとしたデータの原則に従ってデータを整理します。 +- カンマ区切り (CSV) 形式やタブ区切り (TSV) 形式などのテキストベースのスプレッドシート形式について説明します。 + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- 表形式のデータを整理するにはどうすればよいですか? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +> This episode is based on the Data Carpentries's _Data Analysis and +> Visualisation in R for Ecologists_ lesson. + +## 表計算プログラム + +**質問** + +- 優れたデータ統合用にスプレッドシートを使用するための基本的な原則は何でしょうか? + +**客観的** + +- コンピューターがデータセットを + に活用できるようにデータを整理するためのベスト プラクティスについて説明します。 + +**キーポイント** + +- 適切なデータ構成は、あらゆる研究プロジェクトの基礎です。 + +適切なデータ構成は、研究 +の基礎です。 ほとんどの研究者はデータを持っているか、 +シートにデータ入力を行っていません。 スプレッドシート プログラムは、データ テーブルを設計し、非常に基本的 +データ品質管理機能を処理するための非常に便利な +インターフェイスです。 @Broman:2018 も参照してください。 + +### スプレッドシートの概要 + +スプレッドシートはデータ入力に適しています。 したがって、スプレッドシートにはデータ +がたくさんあります。 研究者としての時間の多くは、この「データの検討」段階 +費やされることになります。 とても楽しいわけではありませんが、必要性は +です。 データの編成について考える方法と、より効果的なデータ ラングリングのための +かの実践方法を説明します。 + +### このレッスンで教えられないこと + +- スプレッドシートで _統計_ を行う方法 +- スプレッドシートで _プロット_ を行う方法 +- スプレッドシート プログラムで _コードを記述する_方法 + +これを実行したい場合は、O 発行の Head First +Excel +参考になります。 「ライリー。 + +### なぜスプレッドシートでのデータ分析を教えないのか + +- スプレッドシートでのデータ分析には通常、多くの + 作業が必要です。 パラメーターを変更したり、 + データセットを使用して分析を実行したりする場合は、通常、すべてを手動でやり直す必要があります。 (マクロを作成できることはわかりませ + が、次の点を参照してください。) + +- また、 + の作業に戻りたいときや、誰かが分析の詳細を尋ねたときに、スプレッドシート プログラムで行われた統計分析やプロット分析を追跡したり再現したりすること + 困難です。 + +多くの表計算プログラムが利用可能です。 ほとんどの参加者は主なスプレッドシート プログラムとして +を使用するため、このレッスンで +Excel の例を使用します。 で使用できる表計算プログラムは LibreOffice です。 コマンドはプログラム間 +少し異なる場合がありますが、一般的な考え方は同じです。 + +スプレッドシート プログラムには、研究者としてできる +にする必要のある多くのことが含まれています。 それらは次の目的で使用できます。 + +- データ入力 +- データの整理 +- データのサブセット化と並べ替え +- 統計 +- プロット + +スプレッドシート プログラムはテーブルを使用してデータを表し、表示します。 テーブルとしてフォーマットされたデータ +この章の主要テーマであり、効率的なダウンストリーム分析を +にするために、標準化された方法でデータをテーブルに編成する方法 +見ていきます。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## 課題: 隣人と次の点について話し合ってください。 + +- 研究や + 、または自宅でスプレッドシートを使用したことがありますか? +- スプレッドシートではどのような操作を行っていますか? +- スプレッドシートは何に適していると思いますか? +- スプレッドシート プログラムで誤ってイライラ + たり悲しくなったりするようなことをしたことがありますか? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +### スプレッドシートの問題 + +スプレッドシートはデータ入力には適していますが、実際にはデータ入力以外の目的で +シート プログラムを使用する傾向があります。 これら +を使用して、出版物のデータ テーブルを作成し、概要 +統計を生成し、図を作成します。 + +スプレッドシートでパブリケーション用のテーブルを生成することは +ではありません。多くの場合、パブリケーション用にデータ テーブルをフォーマットするとき、実際にはデータとして読み取ら +ことを意図していない方法で重要な概要統計をレポートすることに +、特殊なフォーマットが必要になることがよくあります。 +(セルを結合し、境界線を作成し、美しくする)。 この種の操作は文書編集ソフトウェア内で行う +をお勧めします。 + +統計と数値を生成する後者の 2 つのアプリケーションは、 +して使用する必要があります。1 スプレッド +プログラムのグラフィカルなドラッグ アンド ドロップの性質のため、 +手順を複製するのが不可能ではないにしても、非常に困難になる可能性があります (元に戻すことはさらに困難です)。特に +の統計や数値により、より複雑な計算が必要な場合はそうです。 さらに、スプレッドシートで計算を行う場合、 +わずかに異なる数式を +の隣接するセルに誤って適用してしまうことがよくあります。 R や SAS などのコマンドライン ベースの統計プログラムを使用する場合、意図的に実行しない限り、データセット内の観測値には計算を適用し、別の観測値には計算を適用しないことは事実上不可能です。 + +### データ入力とクリーニングにスプレッドシートを使用する + +このレッスンでは、 +なスプレッドシート プログラムとして Excel を使用している可能性が高いと仮定します。他にも (OpenOffice の gnumeric、Calc +) があり、機能は似ていますが、Excel が +よく使用されているプログラムであると思われます。生物学者や生物医学の研究者。 + +このレッスンでは次のことについて話します。 + +1. スプレッドシートでのデータテーブルの書式設定 +2. フォーマットの問題 +3. データのエクスポート + +## スプレッドシートでのデータテーブルの書式設定 + +**質問** + +- データを効果的に使用するには、スプレッドシート内のデータをどのようにフォーマットすればよいでしょうか? + +**目的** + +- シートでのデータ入力と書式設定のベスト プラクティスについて説明します。 + +- ベスト プラクティスを適用して、変数と観測値を + シートに配置します。 + +**キーポイント** + +- 生データは決して変更しないでください。 + を加える前に必ずコピーを作成してください。 + +- データをクリーンアップするために実行したすべての手順を + テキスト ファイルに記録します。 + +- きちんとしたデータの原則に従ってデータを整理します。 + +最もよくある間違いは、スプレッドシート プログラムを研究室の +ブックのように扱うことです。つまり、情報を伝えるためにコンテキスト、余白のメモ、データとフィールドの空間 +レイアウトに依存していることです。 人間として、これらのことを (通常は) 解釈できますが、コンピューターは情報 +同じようには見ません。そして、すべての +の意味をコンピューターに説明しない限り (それ +難しい場合があります!)、理解できません。 +データがどのように組み合わされるかを確認できます。 + +コンピューターの力を利用すると、 +効果的かつ高速な方法でデータを管理および分析できますが、その力を使用するには、コンピューターが理解できるようにデータを +する必要があります ( +コンピューターは非常に複雑です)。リテラル)。 + +このため、 +の予備実験からデータの入力を開始する前に、適切にフォーマットされた +をセットアップすることが非常に重要です。 データの整理は研究プロジェクトの +です。 分析全体を通じて +の操作が容易になるか困難になる可能性があるため、データ入力を行う +や実験を設定するときに考慮する価値があります。 +スプレッドシートではさまざまな方法で設定できますが、これらの +選択の一部によっては、 +のプログラムでデータを操作する能力が制限されたり、6 か月後の自分や共同作業者が共同作業したりすることが制限される可能性があります。 +データ。 + +**注:** データ入力とデータ分析に最適なレイアウト/形式 (およびソフトウェアと +) は異なる場合があります。 これを考慮し、理想的にはあるものから +のものへの変換を自動化することが +です。 + +### 分析を追跡する + +スプレッドシートを使用しているとき、データのクリーンアップ +分析を行っているときに、最初のスプレッドシートとは +異なる外観のスプレッドシートが完成することがよくあります。 分析を +したり、査読者や講師が別の分析を要求したときに何をしたかを把握したりするには、次のこと +行う必要があります。 + +- クリーンアップまたは分析されたデータを含む新しいファイルを作成します。 元のデータセット + 変更しないでください。変更すると、どこから始めたのかわからなくなります。 + +- クリーンアップまたは分析で実行した手順を記録します。 実験の他のステップと同様に、これらのステップを追跡する必要があり + 。 データ ファイルと同じフォルダーに保存された + テキスト ファイルでこれを行うことをお勧め + ます。 + +これはスプレッドシート設定の例です。 + +![](fig/spreadsheet-setup-updated.png) + +今日の演習中にこれらの原則を実践してください。 + +バージョン管理はこのコースの範囲外ですが、**バージョンを維持 +方法については、 +['Git'](https://swcarpentry.github.io/git-novice/) の +Carpentries レッスンを参照してください。データを制御**します。 簡単なチュートリアルについてはこの ブログ +投稿 を、より研究指向のユースケースについては +@Perez-Riverol:2016 も参照してください。 + +### スプレッドシートでのデータの構造化 + +データにスプレッドシート プログラムを使用する際の基本ルールは次のとおりです。 + +1. すべての変数を列に入力します。測定対象は「重量」や「温度」 + です。 +2. 各観測値を独自の行に配置します。 +3. 1 つのセルに複数の情報を組み合わせないでください。 場合によっては + それは単なる + つのことのように思えますが、それがそのデータを使用または並べ替えできるようにする唯一の方法であるかどうかを考えてください。 +4. 生データはそのままにしておきます。変更しないでください。 +5. クリーンアップされたデータを CSV + (カンマ区切り値) 形式などのテキストベースの形式にエクスポートします。 これにより、誰でも + を使用できるようになり、ほとんどのデータ リポジトリで必要になります。 + +たとえば、ベルギーのブリュッセルにあるいくつか +病院を訪れた患者からのデータがあります。 彼らは、訪問日、 +、患者の性別、体重、血液型を記録しました。 + +次のようにデータを追跡するとします。 + +![](fig/multiple-info.png) + +問題は、ABO グループと Rhesus グループが同じ「Blood」 +タイプ列にあることです。 したがって、A +グループのすべての観測値を調べたり、ABO グループごとの重み分布を調べたりしたい場合、このデータ設定を使用してこれを行うのは難しいでしょう +。 代わりに、ABO グループと Rhesus +グループを別の列に配置すると、はるかに簡単になることがわかります。 + +![](fig/single-info.png) + +データシートを設定する際の重要なルールは、**列は変数に +され**、**行は観測に使用される**ということです。 + +- 列は変数です +- 行は観測結果です +- セルは個別の値です + +::::::::::::::::::::::::::::::::::::::: challenge + +## 課題: 乱雑なデータセットを取り上げ、それをクリーンアップする方法を説明します。 + +1. [ここ](https://github.com/UCLouvain-CBIO/WSBIM1207/raw/master/data/messy_covid.xlsx) + をクリックして、乱雑なデータセットをダウンロードします。 + +2. スプレッドシート プログラムでデータを開きます。 + +3. タブが 2 つあることがわかります。 このデータには、2020 年の新型コロナウイルス感染症 (COVID-19) の第 + 波と第 2 波の間にブリュッセルのさまざまな病院で記録されたさまざま + 臨床変数が含まれています。 ご覧のとおり、 + データは 3 月と 11 月 + の波では異なる方法で記録されています。 あなたはこのプロジェクトの責任者となり、 + データの分析を開始できるようにしたいと考えています。 + +4. 隣にいる人と一緒に、この + スプレッドシートのどこが間違っているのかを特定してください。 また、最初と 2 番目の Wave タブをクリーンアップし、それらをすべて + つのスプレッドシートにまとめるために必要な手順について + 説明します。 + +**重要:** 最初のアドバイスを忘れないでください。クリーンアップされたデータ用に +ファイル (またはタブ) を作成する場合は、元の +(生の) データを決して変更しないでください。 + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +この演習を終えた後、このデータの +が間違っていたのか、そしてそれをどのように修正するのかをグループで話し合います。 + + + + + + + + + + + + + + + + + + + +::::::::::::::::::::::::::::::::::::::: challenge + +## 課題: データを整理したら、次の質問に答えてください。 + +- 何人の男性と女性が研究に参加しましたか? +- A、AB、B タイプは何人検査されましたか? +- 上記と同様ですが、汚染されたサンプルは無視しますか? +- アカゲザル + と - は何人検査されましたか? +- 何人のユニバーサルドナー (O-) が検査されましたか? +- AB型男性の平均体重はどれくらい? +- さまざまな病院で何件のサンプルが検査されましたか? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +特に R スクリプト +に関する **優れた参考文献**は、_Tidy Data_ 論文 @Wickham:2014 です。 + +## よくあるスプレッドシートのエラー + +**質問** + +- スプレッドシート + のデータの書式設定に関する一般的な課題は何ですか?また、それらを回避するにはどうすればよいですか? + +**目的** + +- 一般的なスプレッドシートの書式設定の問題を認識して解決します。 + +**キーポイント** + +- 1 つのスプレッドシート内で複数のテーブルを使用しないでください。 +- データが複数のタブに分散しないようにします。 +- ゼロはゼロとして記録します。 +- 欠落データを記録するには、適切な null 値を使用します。 +- 情報を伝えたり、スプレッドシートを美しく見せるために書式設定を使用しないでください。 +- コメントは別の列に配置します。 +- 列ヘッダーに単位を記録します。 +- セルには 1 つの情報のみを含めます。 +- 列ヘッダーにはスペース、数字、特殊文字を使用しないでください。 +- データ内では特殊文字を避けてください。 +- メタデータを別のプレーン テキスト ファイルに記録します。 + + + + + + + + + +自分自身のデータ +でなく、共同作業者やインターネットからのデータにも、注意すべき潜在的なエラーがいくつかあります。 エラーや、下流 +データ分析 +結果の解釈に悪影響が及ぶ可能性があることを認識 +ていれば、自分やプロジェクト メンバーがエラーを回避しようとする動機になるかもしれません。 スプレッドシートでデータをフォーマットする方法に +変更を加えると、データのクリーニング +と分析の効率と信頼性に大きな影響 +を与える可能性があります。 + +- [複数のテーブルの使用](#tables) +- [複数のタブの使用](#tabs) +- [ゼロを埋めない](#zeros) +- [問題のある null 値の使用](#null) +- [情報を伝えるために書式設定を使用する](#formatting) +- [書式設定を使用してデータシートを美しく見せる](#formatting_pretty) +- [セル内にコメントまたはユニットを配置する](#units) +- [セルに複数の情報を入力する](#info) +- [問題のあるフィールド名の使用](#field_name) +- [データ内での特殊文字の使用](#special) +- [データテーブルへのメタデータの組み込み](#metadata) + +### 複数のテーブルの使用 {#tables} + +一般的な戦略は、1 つ +スプレッドシート内に複数のデータ テーブルを作成することです。 これはコンピュータを混乱させるので、行わないでください。\ +1 つのスプレッドシート内に複数のテーブルを作成すると、コンピュータにとっては、各行を観測 +として認識するため、物事の間に +た関連付けが描画されることになります。 また、同じフィールド名を +の場所で使用している可能性があり、データを使用可能な形式に +アップすることが困難になります。 以下の例は問題を示しています。 + +![](fig/2_datasheet_example.jpg) + +上の例では、コンピュータは、(たとえば) 行 4 と +、すべての列 A ~ A F が同じサンプルを参照しているとみなして表示します。 この行 +、実際には 4 つの異なるサンプル (5 月 29 日、6 月 12 日、6 月 19 日、および 6 月 +26 日の +つの異なる収集日のそれぞれのサンプル 1) と、計算されたいくつかの概要統計 (平均 (avr) +およびこれら +のサンプルのうち 2 つの標準測定誤差 (SEM))。 他の行にも同様に問題があります。 + +### 複数のタブの使用 {#tabs} + +しかし、ワークブックのタブはどうでしょうか? +データを整理する簡単な方法のように思えますよね? まあ、はい、いいえです。 追加のタブを作成すると、そこにあるデータの接続をコンピュータに認識させることができなく +ます (この接続を確保するには、 +スプレッドシート アプリケーション固有の関数を導入するか、 +スクリプトを導入する必要があります)。 たとえば、測定を行う日ごとに +のタブを作成するとします。 + +これは次の 2 つの理由から良い習慣ではありません。 + +1. 測定を行うたびに新しいタブでデータ + の記録を開始すると、誤って + データに不一致が追加される可能性が高くなります。 + +2. たとえすべての不一致が忍び寄るのを防ぐことができたとしても、 + これらのデータを単一 + データテーブルに結合する必要があるため、 + データを分析する前に余分な手順を追加することになります。 タブ + 結合する方法をコンピュータに明示的に指示する必要があります。また、タブの形式が一貫していない場合は、 + で結合する必要がある場合もあります。 + +次回データを入力するときに、別のタブ +またはテーブルを作成するときは、元のスプレッドシートに別の列を +追加することで、このタブの追加を回避できるかどうか自問してください。 乱雑なデータ ファイルの +では複数のタブを使用しましたが、データを +編成してタブ間で統合する方法がわかりました。 + +の過程でデータシートが非常に長くなる可能性があります。 これにより、スプレッドシートの上部に +ヘッダーが表示されない場合、データの入力が困難になります。 ただし、ヘッダー +行を繰り返さないでください。 これらは簡単にデータに混入し、 +的に問題が発生する可能性があります。 代わりに、列 +ヘッダーを固定する +ことができます。これにより、多くの +行を含むスプレッドシートがある場合でも、それらの行が表示されたままになります。 + +### ゼロを埋めない {#zeros} + +何かを測定するとき、調査でウサギが観察された回数は通常 +である可能性があります。 その列にはほとんどゼロがあるのに、なぜわざわざ +という数字のゼロを書き込むのでしょうか? + +ただし、 +スプレッドシートのゼロと空白のセルには違いがあります。 コンピューターにとって、ゼロは実際にはデータです。 あなたが測ったか、 +なかった。 空白のセルは、測定されていないことを意味し、 +はそれを未知の値 (ヌル +または欠損値とも呼ばれます) として解釈します。 + +スプレッドシートや統計プログラムでは、ゼロであるつもりの +の空白セルが誤って解釈される可能性があります。 観測値 +入力しないことにより、そのデータ +を不明または欠落 (null) として表すようにコンピュータに指示することになります。 これにより、後続の +の計算または分析で問題が発生する可能性があります。 たとえば、単一の null 値を含む一連の数値 +の平均は常に null です ( +は欠落している観測値を推測できないため)。 このうち +であるため、ゼロをゼロとして記録し、真に +欠損データをヌルとして記録することが非常に重要です。 + +### 問題のある null 値 {#null}の使用 + +**例**: -999 またはその他の数値 (またはゼロ) を +に使用すると、欠損データを表します。 + +**解決策**: + +データセット内で null 値が異なる +で表現される理由はいくつかあります。 紛らわしいヌル値が測定装置から自動的に +として記録される場合があります。 その場合、できることは +ではありませんが、ツール +を使用してデータ クリーニングで対処できます 1 +[OpenRefine](https://www.datacarpentry.org/OpenRefine-ecology-lesson/) +前分析。 また、データが存在しないさまざまな理由を伝えるために、 +な null 値が使用されることもあります。 これは取得すべき重要 +情報ですが、実際には 1 つの列を使用して +2 つの情報を取得することになります。 フォーマットを使用して +情報を伝える と同様に、ここでは「data\_missing」のような新しい +列を作成し、その列を使用して +の異なる理由をキャプチャすると良いでしょう。 + +理由が何であれ、不明または欠落しているデータが +として -999、999、または 0 として記録されている場合は問題です。 + +多くの統計プログラムは、これらが欠損 (NULL) 値を表す +であることを認識しません。 これらの値 +がどのように解釈されるかは、データの分析に使用するソフトウェアによって異なります。 明確に定義された一貫性のある null インジケーターを使用することが +です。 + +空白 (ほとんどのアプリケーション) と NA (R の場合) が +選択肢として適しています。 @White:2013 は、記事の中で、さまざまなソフトウェア アプリケーションに対して null 値 +を示すための適切な選択肢について説明しています。 + +![](fig/3_white_table_1.jpg) + +### フォーマットを使用して情報を伝える {#formatting} + +**例**: 分析から +必要があるセル、行、または列を強調表示し、空白の行を残してデータの +分離を示します。 + +![](fig/formatting.png) + +**解決策**: 新しいフィールドを作成して、 +データをエンコードします。 + +![](fig/good_formatting.png) + +### 書式設定を使用してデータシートを美しく見せる {#formatting\_pretty} + +**例**: セルを結合します。 + +**解決策**: 注意しないと、ワークシートを +より美しく見えるように書式設定すると、データ内の +関連付けを認識するコンピュータの機能が損なわれる可能性があります。 セルを結合すると、統計ソフトウェアで +を読み取ることができなくなります。 データを整理する +にセルを結合する必要がないような方法でデータを再構築することを検討してください。 + +### セル {#units}にコメントまたはユニットを配置する + +ほとんどの分析ソフトウェアは Excel や LibreOffice のコメントを表示できないため、 +データ セル内に配置されたコメントによって混乱する可能性があります。 書式設定について +で説明したように、セルに +を追加する必要がある場合は、別のフィールドを作成します。 同様に、セルに単位を含めないでください。理想的には、1 つの列に配置する +の測定値が同じ +単位内にある必要がありますが、何らかの理由でそうでない場合は、別のフィールドを作成し、 +セルの単位を指定します。で。 + +### セル {#info}に複数の情報を入力する + +**例**: A+、 +B+、A- などの ABO グループとアカゲザル グループを 1 つのセルに記録する + +**解決策**: +セルに複数の情報を含めないでください。 これにより、データを分析できる方法が制限されます。\ +の場合、これらの測定値の両方が必要な場合は、 +この情報を含めるようにデータシートを設計します。 たとえば、ABO グループには 1 つの列を含め、Rhesus グループには +つの列を含めます。 + +### 問題のあるフィールド名 {#field\_name} の使用 + +説明的なフィールド名を選択しますが、スペース、 +数字、またはいかなる種類の特殊文字も含めないように注意してください。 スペースは、空白を区切り文字として使用するパーサーによって +て解釈される可能性があり、一部の +プログラムは +数字で始まるテキスト文字列であるフィールド名を好みません。 + +アンダースコア (`_`) はスペースの代わりに使用できます。 +読みやすさを向上させるために、 +名前をキャメルケースで記述することを検討してください (例: ExampleFileName)。 現時点では意味のある略語 +も、6 か月後にはそれほど明確ではなくなる可能性があることに注意してください。ただし、 +が長すぎる名前を付けすぎないでください。 フィールド名に +を含めることで混乱が回避され、他の人がフィールドを簡単に解釈できるようになります。 + +**例** + +| いい名前 | 良い代替品 | 避ける | +| ----------------------------------------------------- | ----------------------------- | ---------------------------- | +| 最高\_温度\_C | 最大温度 | 最高温度 (°C) | +| 降水量\_mm | 降水量 | プレcmm | +| 平均\_年\_成長 | 平均年成長 | 平均成長率/年 | +| | セックス | 男/女 | +| | 重さ | w。 | +| セル\_タイプ | セルタイプ | 細胞の種類 | +| 観察\_01 | 最初の\_観察 | 1回目の観測 | + +### データ {#special}での特殊文字の使用 + +**例**: たとえば、Word または +のアプリケーションからデータを直接コピーするなど、メモを書くときにスプレッドシート プログラムをワード プロセッサ +として扱います。 + +**解決策**: これは一般的な戦略です。 たとえば、セルに +の長いテキストを書き込む場合、スプレッドシートに改行、全角ダッシュ、 +などを含めることがよくあります。 また、Word など +アプリケーションからデータをコピーする場合、書式設定や派手な +標準文字 (左揃えと右揃えの引用符など) +が含まれます。 このデータをコーディング/ +環境またはリレーショナル データベースにエクスポートすると、行が半分に切断されたり、エンコード エラーが発生したりする +、危険なことが発生する可能性があります。 + +一般的なベスト プラクティスは、改行、 +タブ、垂直タブなどの文字の追加を避けることです。 言い換えれば、テキスト セルを、テキストとスペースのみを含めることができる単純な Web フォームで +かのように扱います。 + +### データテーブル {#metadata}へのメタデータの組み込み + +**例**: データ テーブル +の上部または下部に、列の意味、単位、例外などを説明する凡例を追加します。 + +**解決策**: データに関するデータ (「メタデータ」) を記録することは +ではありません。 データセットを +して分析している間は、データセットと親密な関係にあるかもしれませんが、変数「sglmemgp」がグループの単一のメンバー (たとえば +を意味すること、または以前に使用した正確なアルゴリズムを意味することをまだ覚えている可能性は +ありません。変数 +変換するか、派生変数を作成すると、数か月後、1 年後、またはそれ以上かかります。 + +また、他の人があなたのデータを調べたり、使用したりする理由はたくさんあります。あなたの発見を理解するため、 +を検証するため、 +提出された出版物をレビューするため、結果を再現するため、 +同様の研究を計画するため、さらには他の人がアクセスしたり +利用できるようにデータをアーカイブします。 デジタルデータは定義上、 +可読ではありませんが、その意味を理解することは +の仕事です。 研究の収集段階および分析段階でデータを文書化することの重要性は、特に研究が +記録の一部となる場合には +過大評価することはできません +。 + +ただし、データファイル +自体にはメタデータを含めないでください。 論文や補足ファイルの表とは異なり、メタデータ ( +形式) はデータ ファイルに含めるべきではありません。この情報はデータではなく、 +データを含めるとコンピューター プログラムがデータ ファイルを解釈する +が混乱する可能性があるためです。 むしろ、メタデータは、データ ファイルと同じディレクトリに別のファイルとして保存する必要があります。できればファイルと明確に関連付けられる名前を付けてプレーン テキスト形式で保存する必要があります。 メタデータ ファイルはフリー テキスト形式であるため、コメント、単位、 +値のエンコード方法に関する情報などをエンコードすることも +ます。これらの情報は文書化するには重要ですが、データ ファイルの +設定を混乱させる可能性があります。 + +さらに、ファイルまたはデータベース レベルのメタデータは、データセットを構成するファイルが相互に +ように関連するかを記述します。どのような形式であるか。 +は、以前のファイルに優先されるか、または以前のファイルによって置き換えられるか。 +フォルダー レベルの readme.txt ファイルは、プロジェクト内のすべて +ファイルとフォルダーを説明する古典的な方法です。 + +(メタデータに関するテキストは、EDINA および +大学データ ライブラリによるオンライン コース Research Data +[MANTRA](https://datalib.edina.ac.uk/mantra) から改変されました。 MANTRA は クリエイティブ コモンズ +表示 4.0 国際 +ライセンス に基づいてライセンスされています。 + +## データのエクスポート + +**質問** + +- ストリーム アプリケーションに役立つ方法でスプレッドシートからデータをエクスポートするにはどうすればよいでしょうか? + +**目的** + +- スプレッドシート データをユニバーサル ファイル形式で保存します。 +- スプレッドシートから CSV ファイルにデータをエクスポートします。 + +**キーポイント** + +- 一般的なスプレッドシート形式で保存されたデータは、データ分析ソフトウェアに + 読み込まれないことが多く、 + にエラーが生じます。 + +- スプレッドシートから CSV や TSV などの形式にデータをエクスポートすると、ほとんどのプログラムで一貫して使用できる形式でデータが + になります。 + +分析に使用するデータを Excel +既定のファイル形式 (Excel +バージョンに応じて `*.xls` または `*.xlsx`) で保存することはお勧めできません。 なぜ? + +- これは独自の形式であり、 + 的にはファイルを開くことが不可能では + にしても不便になる技術が存在しなくなる (または十分にまれになる) 可能性があるためです。 + +- 他の表計算ソフトウェアでは、 + の Excel 形式で保存されたファイルを開くことができない場合があります。 + +- Excel のバージョンが異なるとデータの処理方法が異なる場合があり、 + 整合が発生する可能性があります。 [日付](https://datacarpentry.org/spreadsheet-ecology-lesson/03-dates-as-data/index.html) + は、データ ストレージにおける不整合の十分に文書化された例です。 + +- 最後に、データをデータ リポジトリに + することを要求するジャーナルや補助金機関が増えています。また、そのほとんどは Excel 形式を受け入れ + ん。 + で説明する形式のいずれかである必要があります。 + +- 上記の点は、LibreOffice / Open Office で使用されるオープン データ + 形式などの他の形式にも当てはまります。 これらの形式は + ではなく、 + ソフトウェア パッケージによって同じ方法で解析されません。 + +データを汎用的でオープンな静的形式で保存すると、この問題に +するのに役立ちます。 タブ区切り (タブ区切り値または TSV) または +カンマ区切り (カンマ区切り値または CSV) を試してください。 CSV ファイルは、列がカンマで区切られたプレーン +テキスト ファイルです。したがって、「カンマ +で区切られた値」または CSV と呼ばれます。 Excel/SPSS/などと +した CSV ファイルの利点ファイルは、TextEdit や +などのプレーン テキスト エディタを含む、ほぼすべてのソフトウェア +を使用して CSV ファイルを開いて読み取ることができるということです。 CSV ファイル内のデータは、SQLite や R などの他 +形式や環境にも簡単にインポートできます。CSV +ファイルを使用する場合、特定の高価なプログラムの +のバージョンに縛られることがないので、最大限の移植性と +性を実現するために使用するフォーマット。 ほとんどのスプレッドシート プログラムは +などの区切りテキスト形式で簡単に保存できますが、ファイルのエクスポート +に警告が表示される場合があります。 + +Excel で開いたファイルを CSV 形式で保存するには: + +1. 上部のメニューから「ファイル」と「名前を付けて保存」を選択します。 +2. [形式] フィールドのリストから、[カンマ区切りの + 値] (`*.csv`) を選択します。 +3. ファイル名と + する場所を再確認し、「保存」をクリックします。 + +下位互換性に関する重要な注意: +ファイルは Excel で開くことができます。 + +```{r, results="markup", fig.cap="Saving an Excel file to CSV.", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +Knitr::include_graphics("fig/excel-to-csv.png") +``` + +**R と `xls` に関するメモ**: `xls` +ファイル (および Google スプレッドシート) を読み取ることができる R パッケージがあります。 「xls」ドキュメント内の +ワークシートにアクセスすることも可能です。 + +**しかし** + +- これらの中には Windows でのみ動作するものもあります。 +- これは、データ分析 R コードの追加の複雑さ/依存性を + して、(単純だが手動の) `csv` へのエクスポートを置き換えることに相当します。 +- データ形式のベスト プラクティスは引き続き適用されます。 +- `csv` (または類似のもの) が + では不十分である正当な理由は本当にあるのでしょうか? + +### カンマに関する注意事項 + +一部のデータセットでは、データ値自体にカンマ +(,) が含まれる場合があります。 その場合、使用しているソフトウェア (Excel を含む) により、列内のデータが誤って表示される可能性が +ます。 これは、データ値の一部であるカンマの +が +区切り文字として解釈されるためです。 + +たとえば、データは次のようになります。 + +``` +種 ID、属、種、分類群 +AB、Amphispiza、bilineata、鳥類 +AH、Ammospermophilus、harrisi、げっ歯類、国勢調査されていない +AS、Ammodramus、savannarum、鳥類 +BA、Baiomys、taylori、げっ歯類 +``` + +レコード「AH,Ammospermophilus,harrisi,Rodent, not censused」では、「taxa」の値 +コンマが含まれています (「Rodent, not censused」)。 上記を Excel (または他のスプレッドシート プログラム) に読み込むために +を試みると、 +のような結果が得られます。 + +```{r, results="markup", fig.cap="The risks of having commas inside comma-separated data.", echo=FALSE, purl=FALSE, out.width="80%", fig.align="center"} +Knitr::include_graphics("fig/csv-mistake.png") +``` + +`taxa` の値は (1 つの列 `D` に +を入れる代わりに) 2 つの列に分割されました。 これはさらに多数の +エラーに伝播する可能性があります。 たとえば、追加の列は、欠損値が多数ある (適切なヘッダーがない) 列 +として解釈されます。 +に加えて、行 3 のレコードの列 `D` の値 (つまり、'taxa' の値にカンマが含まれている +の値) も正しくなくなりました。 + +データを「csv」形式で保存し、 +データ値にカンマが含まれる可能性があることが予想される場合は、値を引用符 ("") で囲むことで、上記 +で説明した問題を回避できます。 このルールを適用すると、 +データは次のようになります。 + +``` +種 ID、属、種、分類群 +"AB"、"Amphispiza"、"bilineata"、"Bird" +"AH"、"Ammospermophilus"、"harrisi"、"げっ歯類、国勢調査されていない" +"AS"、"Ammodramus" 、"サバンナルム"、"鳥" +"BA"、"バイオミス"、"テイロリ"、"げっ歯類" +``` + +Excel では +引用符の外側にあるカンマのみが区切り文字として使用されるため、このファイルを Excel で「csv」として開いても、余分な +列は生成されません。 + +あるいは、カンマを含むデータを操作している場合、 +シートで作業するときに別の区切り文字を使用する必要がある可能 +があります[^decsep]。 この場合、区切り文字としてタブを使用し、TSV ファイルを扱う場合は +使用することを検討してください。 TSV ファイルは、CSV ファイルと同じ方法でスプレッドシート +プログラムからエクスポートできます。 + +[^decsep]: これは、カンマが小数点の + として使用されるヨーロッパの + 諸国に特に関係します。 このような場合、 + csv ファイルのデフォルト値の区切り文字はセミコロン (;) になるか、値は体系的に引用符で囲まれた + になります。 + +データ +の値が "" に含まれていないものの、区切り文字 +とデータ値の一部としてカンマが含まれている既存のデータセットを操作している場合は、データ クリーニングに関する重大な問題 +に直面する可能性があります。 扱っているデータセットに +百または数千のレコードが含まれている場合、それらを手動でクリーンアップする ( +データ値からカンマを削除するか、値を +引用符 ("") で囲む) と、何時間もかかるだけではありません。ただし、誤って +のエラーが発生する可能性があります。 + +データセットのクリーンアップは、多くの +分野における主要な問題の 1 つです。 このアプローチは、ほとんどの場合、特定 +コンテキストに依存します。 ただし、スクリプトを作成して実行するなど、 +化された方法でデータをクリーンアップすることをお勧めします。 +Python と R のレッスンは、 +するスクリプトを構築するためのスキルを開発するための基礎を提供します。 + +## まとめ + +```{r analysis, results="asis", fig.margin=TRUE, fig.cap="A typical data analysis workflow.", fig.width=7, fig.height=4, echo=FALSE, purl=FALSE} +knitr::include_graphics("fig/analysis.png") +``` + +典型的なデータ分析ワークフローは、上の図 +に示されており、データは繰り返し変換、視覚化、モデル化されます。 この +の繰り返しは、データが理解されるまで複数回繰り返されます。 ただし、 +の実際のケースでは、実際にデータを分析して理解すること +ではなく、データのクリーンアップと準備 +にほとんどの時間が費やされます。 + +変換/視覚化/モデルのサイクルを高速で +回繰り返すアジャイルなデータ分析ワークフローは、データが予測可能な方法で +されており、データを調べたり +したりすることなく推論できる場合にのみ実現可能です。それ。 + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- 適切なデータ構成は、あらゆる研究プロジェクトの基礎です。 + +:::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/ja/episodes/20-r-rstudio.Rmd b/locale/ja/episodes/20-r-rstudio.Rmd new file mode 100644 index 000000000..bec8f597e --- /dev/null +++ b/locale/ja/episodes/20-r-rstudio.Rmd @@ -0,0 +1,654 @@ +--- +source: Rmd +title: RとRStudio +teaching: 30 +exercises: 0 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- RStudio スクリプト、コンソール、環境、およびプロットペインの目的について説明します。 +- Rプロジェクトとして一連の分析のためのファイルとディレクトリを整理し、作業ディレクトリの目的を理解する。 +- RStudio 組み込みのヘルプインターフェイスを使用して、R 関数の詳細情報を検索します。 +- Rのユーザーコミュニティとトラブルシューティングのために十分な情報を提供する方法を示す。 + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- RとRStudioとは何ですか? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +> このエピソードは、Data Carpentriesの_Data Analysis and +> Visualisation in R for Ecologists_レッスンに基づいています。 + +## Rとは? RStudioとは何ですか? + +R](https://www.r-project.org/)という用語は、 +_プログラミング言語_、統計計算_のための_環境 +、それを使って書かれたスクリプトを解釈する_ソフトウェア_を指すのに使われる。 + +[RStudio](https://rstudio.com)は現在、Rスクリプトを書くだけでなく、R +ソフトウェア[^plainr]と対話するための非常に人気のある方法です。 RStudio を正しく機能させるには、R と +が必要です。 + +[^plainr]: コマンドライン + コンソールから直接Rを使うのとは対照的だ。 + 、Rとインターフェイスし統合するソフトウェアは他にもあるが、RStudioは非常に高度な機能を数多く備えながら、特に初心者向け + 。 + +RStudio IDE Cheat +Sheet](https://raw.githubusercontent.com/rstudio/cheatsheets/main/rstudio-ide.pdf) +、ここで説明するよりもはるかに多くの情報を提供していますが、キーボードショートカットを学んだり、新しい機能を発見したりするのに便利です。 + +## なぜRを学ぶのか? + +### Rはポインティングやクリックを多用しない。 + +学習曲線は他のソフトウェアよりも急かもしれないが、 +Rを使えば、分析結果は +のポインティングとクリックの連続を覚えることに依存するのではなく、代わりに +の一連のコマンドを書くことに依存する! +そのため、より多くのデータを収集したため、 +分析をやり直したい場合、 +結果を得るためにどのボタンをどの順番でクリックしたかを覚えておく必要はない。スクリプトを再度実行するだけでよい。 + +スクリプトを使用することで、分析で使用したステップが明確になり、 +、書いたコードを他の誰かが検査することができ、 +フィードバックを与え、間違いを発見することができる。 + +スクリプトを使って仕事をすることで、自分がやっている +の内容をより深く理解することになり、自分が使っている +メソッドの学習と理解が容易になる。 + +### Rコードは再現性に優れている + +再現性とは、同じデータセットから同じ解析コード( +)を使ったときに、他の誰か(未来の自分を含む)が +、同じ結果を得られることを意味する。 + +Rは他のツールと統合し、 +のコードから原稿やレポートを作成することができる。 さらにデータを集めたり、データセットの誤りを修正したりすると、原稿や報告書の +図や統計検定が自動的に更新されます。 +。 + +ジャーナルや研究助成機関では、 +、再現性のある分析を求めるところが増えている。Rを知っていれば、このような +。 + +### Rは学際的で拡張性がある + +機能を拡張するためにインストールできる10000以上のパッケージ[^whatarepkgs]により、Rは、 +多くの科学分野からの統計的アプローチを組み合わせることができるフレームワークを提供し、 +データの分析に必要な分析フレームワークに最適です。 例えば、 +Rには画像分析、GIS、時系列、集団 +遺伝学、その他多くのパッケージがある。 + +[^whatarepkgs]: すなわち、バイオインフォマティクスのデータ解析など、Rに新しい機能を付与するアドオンである。 + 。 + +```{r, fig.cap="Exponential increase of the number of packages available on [CRAN](https://cran.r-project.org/), the Comprehensive R Archive Network. From the R Journal, Volume 10/2, December 2018.", echo=FALSE, message=FALSE} +knitr::include_graphics("fig/cran.png") +``` + +### Rはあらゆる形や大きさのデータを扱う + +Rで学ぶスキルは、 +データセットの大きさに合わせて簡単にスケールアップできる。 データセットの行数が数百行であろうと数百万行であろうと、 +、大差はないだろう。 + +Rはデータ分析用に設計されている。 欠損データや統計的 +因子の取り扱いを便利にする特別なデータ構造 +とデータ型が付属している。 + +Rは、スプレッドシート、データベース、その他多くのデータ形式、 +、コンピュータ上またはウェブ上に接続することができます。 + +### Rは高品質のグラフィックを作成する + +Rのプロット機能は充実しており、 +データからのメッセージを最も効果的に伝えるために、グラフのあらゆる面を調整することができる。 + +### Rは大きく歓迎されるコミュニティ + +何千人もの人々が毎日Rを利用している。 彼らの多くは、メーリングリストやStack +Overflowのようなウェブサイト、またはRStudio +communityを通じて、 +。 こうした広範なユーザー・コミュニティは、 +、バイオインフォマティクスのような専門分野にも広がっている。 Rコミュニティのそのようなサブセットの1つが、[Bioconductor](https://bioconductor.org/)である。"現在および将来の生物学的アッセイからのデータの "分析と理解のための科学的プロジェクトである。 このワークショップは、Bioconductor コミュニティのメンバーによって開発されました。Bioconductor についての詳細は、関連ワークショップ ["The Bioconductor Project"](https://carpentries-incubator.github.io/bioc-project/) をご覧ください。 + +### Rは無料であるだけでなく、オープンソースでクロスプラットフォームである。 + +Rがどのように動作するかは、誰でもソースコードを調べることができる。 この +の透明性により、ミスが発生する可能性は低くなり、もしあなた(または +他の誰か)がミスを発見したら、バグを報告して修正することができる。 + +## RStudioを使いこなす + +まずは[RStudio](https://www.rstudio.com/)について学んでみよう。 +は +R を扱うための統合開発環境(IDE)だ。 + +RStudio IDE オープンソース製品は、Affero General +Public License (AGPL) v3の下でフリーです。 +RStudio IDE は、Posit, Inc.の商用ライセンスおよび +優先メールサポートでもご利用いただけます。 + +RStudio IDE を使ってコードを書き、 +コンピュータ上のファイルを操作し、これから作成する変数を検査し、 +生成するプロットを視覚化する。 RStudioは他にも +(例:バージョン管理、パッケージの開発、Shynyアプリの作成)にも使えます。 +ワークショップでは取り上げません。 + +```{r, results="markup", fig.cap="RStudio interface screenshot. Clockwise from top left: Source, Environment/History, Files/Plots/Packages/Help/Viewer, Console.", echo=FALSE, purl=FALSE, out.width="100%", fig.align="center"} +knitr::include_graphics("fig/rstudio-screenshot.png") +``` + +RStudio ウィンドウは 4 つの「ペイン」に分かれています: + +- スクリプトとドキュメントの **ソース** ( + のデフォルトレイアウトでは左上) +- あなたの**環境/歴史**(右上)、 +- あなたの**Files/Plots/Packages/Help/Viewer**(右下)、そして +- R **コンソール**(左下)。 + +これらのペインの配置とその内容はカスタマイズすることができます( +メニューの `Tools -> Global Options -> Pane Layout` を参照してください)。 + +RStudioを使う利点の1つは、コードを書くために必要なすべての情報( +)が1つのウィンドウで利用できることです。 さらに、 +多くのショートカット、**オートコンプリート**、およびRでの開発中に使用する主な +ファイルタイプの**ハイライト**により、RStudioは +の入力を容易にし、エラーを少なくします。 + +## セットアップ + +関連するデータ、分析、テキスト( +)のセットは、**working +directory**と呼ばれる1つのフォルダに自己完結させておくのがよい習慣である。 このフォルダー内のすべてのスクリプトは、 +**相対パス** を使用して、 +ファイルがプロジェクト内のどこにあるかを示すことができます( +ファイルが特定のコンピューター上のどこにあるかを示す絶対パスとは異なります)。 この方法で作業することで、 +、自分のコンピュータ上でプロジェクトを移動したり、 +他の人と共有したりすることが、基盤となるスクリプト +がまだ動くかどうかを心配することなく、とても簡単になる。 + +RStudioは、"Projects" +インターフェイスを通じて、このような作業を行うための便利なツールセットを提供しています。このツールは、作業ディレクトリを作成するだけでなく、 +その場所を記憶し(すぐに移動できるようになります)、 +カスタム設定や開いているファイルを保存して、 +休憩後に作業を再開しやすくすることもできます。 この +チュートリアルのための "Rプロジェクト "の作成手順を以下に示す。 + +1. RStudioを起動します。 +2. File`メニューの下にある`New project`をクリックする。 新規ディレクトリ`を選択し、 + `新規プロジェクト`を選択する。 +3. この新しいフォルダ(または「ディレクトリ」)の名前を入力し、 + 便利な場所を選択します。 これはこのセッション (またはコース全体) の **作業ディレクトリ** + になります (例 `bioc-intro`)。 +4. Create project\`をクリックする。 +5. (オプション)RStudio でワークスペースを保存しない設定にします。 + +RStudioのデフォルトの環境設定は一般的にうまく機能しますが、ワークスペースを +.RDataに保存するのは、特に大きなデータセットを扱う場合は面倒です。 +これをオフにするには、「ツール」→「グローバル・オプション」で、終了時に「ワークスペースを.RDataに保存する」 +「決してしない」オプションを選択します。 + +```{r, results="markup", fig.cap="Set 'Save workspace to .RData on exit' to 'Never'", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/rstudio-preferences.png") +``` + +ウィンドウズと他のオペレーティング・システム間の文字エンコーディングの問題](https://yihui.name/en/2018/11/biggest-regret-knitr/)を避けるため、 +、デフォルトでUTF-8を設定します: + +```{r, results="markup", fig.cap="Set the default text encoding to UTF-8 to save us headache in the coming future. (Figure from the link above).", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/utf8.png") +``` + +### 作業ディレクトリの整理 + +プロジェクト全体で一貫性のあるフォルダ構造を使うことで、 +、整理整頓がしやすくなり、将来的に探し出したりファイルしたりするのも簡単になります。 この +、複数のプロジェクトを抱えているときには特に役立つ。 一般的に、 +、\***スクリプト**、\***データ**、\***ドキュメント**用のディレクトリ(フォルダ)を作成することができます。 + +- **data/**\* このフォルダは、生データと、特定の分析に必要な中間データセット( + )を保存するために使用します。 + 透明性と + [出所](https://en.wikipedia.org/wiki/Provenance)のために、 + _常に_ 生データのコピーにアクセスできるようにしておき、 + データのクリーンアップと前処理をできるだけプログラム的に(つまり、手作業ではなく + スクリプトで)行うべきである。 生データ + 、加工データから切り離すのも良いアイデアだ。 例えば、 + `data/raw/tree_survey.plot1.txt`と`...plot2.txt`のファイルを、 + `scripts/01.preprocess.tree_survey.R`スクリプトによって生成された`data/processed/tree.survey.csv`ファイルとは別に + 。 +- **`documents/`** ここは、アウトライン、下書き、 + 、その他のテキストを保管する場所になります。 +- \*\*scripts/`** (または `src\`) この場所には、さまざまな分析やプロット用の R + スクリプトを保存し、 + 関数用の別フォルダを作成することもできます(詳しくは後述します)。 + +あなたのプロジェクトの必要性に応じて、追加のディレクトリやサブディレクトリが必要になるかもしれないが、これらはあなたの作業用 +ディレクトリのバックボーンを形成するはずである。 + +```{r, results="markup", fig.cap="Example of a working directory structure.", echo=FALSE, purl=FALSE, out.width="100%", fig.align="center"} +knitr::include_graphics("fig/working-directory-structure.png") +``` + +このコースでは、生データを保存するために `data/` フォルダが必要です。 +、データを +CSV ファイルとしてエクスポートする方法を学ぶために `data_output/` フォルダを使用し、図を保存するために `fig_output/` フォルダを使用します。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## 課題:プロジェクトのディレクトリ構造を作る + +画面右側の`Files`タブで、`New Folder`をクリックし、 +、新しく作成した作業ディレクトリー +(例:`~/bioc-intro/data`)の中に`data`という名前のフォルダーを作成します。 (あるいは、Rのコンソール +で `dir.create("data")` とタイプする)。 これらの操作を繰り返して、`data_output/` と +`fig_output` フォルダーを作成する。 + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +スクリプトは作業ディレクトリのルート +に置くことにする。使用するのは1つのファイルだけだし、 +事が簡単になるからだ。 + +作業ディレクトリはこのようになっているはずだ: + +```{r, results="markup", fig.cap="How it should look like at the beginning of this lesson", echo=FALSE, purl=FALSE, out.width="100%", fig.align="center"} +knitr::include_graphics("fig/r-starting-how-it-should-look-like.png") +``` + +**プロジェクト管理**は、バイオインフォマティクス・プロジェクトにも適用できる。 +[^bioindatascience]。 William Noble (@Noble:2009)は、 +以下のディレクトリ構造を提案している: + +[^bioindatascience]: このコースでは、バイオインフォマティクスを、 + 、生物学的または生物医学的データに適用されるデータサイエンスと考える。 + +> ディレクトリ名は大きな書体で、ファイル名は小さな +> 。 ここに掲載したのは、その一部である。 なお、 +> の日付は、--`というフォーマットになっているので、 +> 時系列順に並べ替えることができる。 ソースコード`src/ms-analysis.c`がコンパイルされて`bin/ms-analysis`が作成され、`doc/ms-analysis.html`に文書化されている。 データ・ディレクトリ +> にある`README`ファイルには、誰がどの URL から +> の日付にデータ・ファイルをダウンロードしたかが明記されている。 ドライバスクリプト`results/2009-01-15/runall`は自動的に +> 3つのサブディレクトリ split1、split2、split3 を生成する。 +> は3つのクロスバリデーション分割に対応する。 `bin/parse-sqt.py`スクリプトは`runall\` ドライバ +> スクリプトの両方から呼び出される。 + +```{r bioinfoproj, fig.cap="Directory structure for a sample bioinformatics project.", out.width="100%", echo=FALSE} +knitr::include_graphics("fig/noble-bioinfo-project.png") +``` + +よく定義され、よく文書化された +プロジェクトのディレクトリの最も重要な側面は、 +プロジェクト[^futureself]をよく知らない人が、次のことをできるようにすることである。 + +1. どのようなプロジェクトなのか、どのようなデータが入手可能なのか、どのような + 分析が行われ、どのような結果が出たのかを理解すること、そして最も重要なことは、 + を理解することである。 + +2. 新しいデータで、あるいは + 分析パラメーターの一部を変更して、分析を繰り返す。 + +[^futureself]: その誰かとは、 + 、分析が実行された数カ月後、あるいは数年後に、 + 、未来のあなた自身である可能性が高い。 + +### 作業ディレクトリ + +作業ディレクトリは理解すべき重要な概念である。 Rがファイルを探して保存する +。 +プロジェクトのコードを書くときは、作業ディレクトリのルート +に関連するファイルを参照し、この +構造内のファイルだけが必要です。 + +RStudioプロジェクトを使用すると、この作業が簡単になり、 +ディレクトリが適切に設定されます。 もし確認する必要があれば、 +`getwd()` を使うことができる。 何らかの理由で作業ディレクトリが +のようになっていない場合は、RStudio のインターフェイスで +ファイルブラウザーで作業ディレクトリがあるべき場所に移動し、 +青い歯車のアイコン `More` をクリックし、`Set As Working Directory` を選択して変更することができます。 +あるいは、`setwd("/path/to/working/directory")`を使って、 +作業ディレクトリをリセットすることもできる。 しかし、あなたのスクリプトには、 +、この行を含めるべきではありません。なぜなら、他の誰かのコンピューターで失敗してしまうからです。 + +\*\*例 + +以下のスキーマは作業ディレクトリ `bioc-intro` と +`data` と `fig_output` のサブディレクトリ、そして後者にある2つのファイルを表しています: + +``` +bioc-intro/data/ + /fig_output/fig1.pdf + /fig_output/fig2.png +``` + +もし作業ディレクトリにいれば、相対パス `bioc-intro/fig_output/fig1.pdf` か、 +絶対パス `/home/user/bioc-intro/fig_output/fig1.pdf` を使って `fig1.pdf` +ファイルを参照することができます。 + +もし `data` ディレクトリにいたとしたら、相対パス +`../fig_output/fig1.pdf` か、同じ絶対パス +`/home/user/bioc-intro/fig_output/fig1.pdf` を使うことになる。 + +## Rとの対話 + +プログラミングの基本は、私たちが +、コンピュータが従うべき命令を書き記し、その +命令に従うようコンピュータに指示することである。 私たちがRで命令を書く、つまり_コード_を書くのは、それが +、コンピューターも私たちも理解できる共通言語だからだ。 私たちは +を_コマンド_と呼び、それらのコマンドを_実行_(_実行_とも呼ぶ)することによって、 +の指示に従うようにコンピュータに指示する。 + +Rと対話する主な方法は2つある: +**コンソール**を使う方法と、**スクリプト**( +あなたのコードを含むプレーンテキストファイル)を使う方法である。 コンソールペイン(RStudioでは左下のパネル)は、 +、R言語で書かれたコマンドを入力し、 +、コンピュータによって即座に実行される場所です。 また、 +、実行されたコマンドの結果が表示される場所でもある。 コンソールに直接 +コマンドを入力し、`Enter`を押すことで、それらの +コマンドを実行することができますが、セッションを閉じると忘れてしまいます。 + +コードとワークフローを再現できるようにしたいので、 +、スクリプトエディターで必要なコマンドを入力し、 +スクリプトを保存する方がよい。 こうすることで、私たちがしたことの完全な記録が残る。 +、誰にでも(未来の自分も含めて!)。 は、 +の結果を自分のコンピューターで簡単に再現できる。 ただし、スクリプトに +、単にコマンドを入力しただけでは自動的に_実行_されないことに注意してほしい。 +、コンソールに送信して実行させる必要がある。 + +RStudio ではスクリプトエディター +から `Ctrl` + `Enter` ショートカット(Mac では `Cmd` + `Return` で +も可)で直接コマンドを実行できます。 Ctrl`+`Enter\`を押すと、スクリプトの現在の行のコマンド(カーソルで +を示す)、または現在選択されているテキスト +のすべてのコマンドがコンソールに送られ、実行される。 その他のキーボードショートカットはRStudio +cheatsheet about RStudio +IDEを参照してください。 + +分析のある時点で、 +変数の内容やオブジェクトの構造をチェックしたくなるかもしれない。必ずしもスクリプトに +の記録を残しておく必要はない。 これらのコマンドを入力し、コンソールで直接 +。 RStudio には `Ctrl` + `1` と +`Ctrl` + `2` のショートカットがあり、スクリプトと +のコンソールペイン間をジャンプすることができます。 + +Rがコマンドを受け付ける準備ができたら、Rコンソールに `>` プロンプトが表示される。 +コマンドを受信すると(タイプ、コピーペースト、またはスクリプト +エディターから `Ctrl` + `Enter` を使って送信)、R はそれを実行しようとします。 +準備ができると、結果を表示し、 +新しいコマンドを待つために新しい `>` プロンプトで戻ってきます。 + +Rがまだ +、データの入力を待っている場合は、コンソールに`+`プロンプトが表示されます。 これは、 +、完全なコマンドの入力が終わっていないことを意味する。 これは、 +、括弧や引用符を「閉じて」いないからです。つまり、 +、左括弧と右括弧の数や、 +、開閉引用符の数が同じではないからです。 このようなことが起こり、 +、コマンドを入力し終わったと思った場合、コンソール +ウィンドウ内をクリックし、`Esc`を押してください。これにより、不完全なコマンドがキャンセルされ、 +`>`プロンプトに戻ります。 + +## コース中やコース終了後にさらに学ぶには? + +このコースで扱う内容は、あなた自身の +研究のためにデータを分析するために R をどのように使うことができるかを、 +初めに体験していただくものです。 しかし、データセットのクリーニング、統計的手法の使用、 +、美しいグラフィックスの作成[^inthiscoure]など、 +の高度な操作を行うには、さらに学ぶ必要がある。 +Rに習熟し、効率的に使えるようになるための最良の方法は、他のツールと同様、Rを使って +実際の研究課題に取り組むことである。 初心者の場合、ゼロからスクリプトを書かなければならないのは、 +困難に感じるかもしれない。 +多くの人が自分のコードをオンラインで公開していることを考えると、 +自分の目的に合うように既存のコードを修正することで、簡単に始めることができるかもしれない。 + +[^inthiscoure]: ここでは、これらのほとんど(統計学を除く) + を紹介するが、Rで可能なこと + の富の表面をかすめることしかできない。 + +```{r kitten, results="markup", echo=FALSE, purl=FALSE, out.width="400px", fig.align="center"} +knitr::include_graphics("fig/kitten-try-things.jpg") +``` + +## 助けを求める + +### RStudio 組み込みのヘルプインターフェイスを使用して、R 関数の詳細情報を検索します。 + +```{r rstudiohelp, fig.cap="RStudio help interface.", results="markup", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/rstudiohelp.png") +``` + +RStudio ヘルプ +インターフェイスを使用するのが、ヘルプを得る最も早い方法の1つです。 このパネルはデフォルトで RStudio の右下 +パネルにあります。 スクリーンショットに見られるように、 +"Mean "という単語を入力すると、RStudioは +、あなたが興味を持ちそうな候補もいくつか出そうとする。 説明文は +ウィンドウに表示される。 + +### 使いたい関数の名前はわかっているが、その使い方がわからない。 + +特定の関数、例えば`barplot()`のヘルプが必要な場合は、 +: + +```{r, eval=FALSE, purl=TRUE} +バープロット +``` + +引数の名前を思い出す必要がある場合は、次のようにすればよい: + +```{r, eval=FALSE, purl=TRUE} +引数(lm) +``` + +### Xを行う関数を使いたい。そのための関数があるはずだが、どれがあるのかわからない...。 + +特定のタスクを実行する関数を探している場合は、 +`help.search()`関数を使用することができます。この関数は二重の疑問符 \`? +しかし、これはインストールされているパッケージの中から、検索リクエストと +一致するヘルプページを探すだけです。 + +```{r, eval=FALSE, purl=TRUE} +クルスカル +``` + +探しているものが見つからない場合は、 +[rdocumentation.org](https://www.rdocumentation.org)のウェブサイトを使うことができます。このウェブサイトは、利用可能なすべてのパッケージのヘルプファイルから +を検索します。 + +最後に、一般的なグーグルやインターネット検索で "R \" を検索すると、多くの場合、 +適切なパッケージ・ドキュメントにたどり着くか、 +他の誰かがすでに質問している有益なフォーラムにたどり着く。 + +### 動けないんだ...。 理解できないエラーメッセージが表示されます。 + +エラーメッセージをググることから始めよう。 +というのも、多くの場合、パッケージ開発者はRが提供するエラー・キャッチに依存しているからである。 +、一般的なエラー・メッセージが表示されることになるが、これは +の問題を診断するのにあまり役に立たないかもしれない(例えば、"subscript out of bounds")。 メッセージが非常に一般的なものであれば、 +、使用している関数やパッケージの名前を +クエリに含めることもできる。 + +しかし、Stack Overflowをチェックする必要がある。 r]\`タグを使って検索する。 ほとんどの +の質問にはすでに答えが出されているが、 +の答えを見つけるために、検索で適切な +の言葉を使うことが課題である: + +[http://stackoverflow.com/questions/tagged/r](https://stackoverflow.com/questions/tagged/r) + +R言語入門](https://cran.r-project.org/doc/manuals/R-intro.pdf) +も、プログラミング経験の少ない人にとっては内容が濃いかもしれないが、R言語の基礎を理解するには良い +場所である。 + +R FAQ](https://cran.r-project.org/doc/FAQ/R-FAQ.html)は密度が濃く、技術的である。 +、しかし有用な情報が満載である。 + +### 助けを求める + +誰かに助けてもらうために重要なのは、相手があなたの問題( +)を素早く把握することだ。 +、どこに問題がありそうかをできるだけ簡単に特定できるようにすべきだ。 + +あなたの問題を説明するために、正しい言葉を使うようにしてください。 例えば、 +パッケージはライブラリとは違う。 ほとんどの人は、 +、あなたが言いたかったことを理解するだろうが、意味の違いについて本当に強い感情を持つ人もいる +。 重要なのは、 +、あなたを助けようとする人々を混乱させる可能性があるということだ。 +できるだけ正確に問題を説明してください。 + +可能であれば、うまくいかないことを単純な例(再現可能な +)にまで落とし込むようにする。 もし、あなたが50000行10000列のデータではなく、非常に小さなデータ +フレームを使って問題を再現できるのであれば、 +その小さなデータを問題の説明とともに提供してください。 適切な場合には、 +、あなたのやっていることを一般化して、 +分野に関係のない人でも質問を理解できるようにする。 例えば、 +実際のデータセットのサブセットを使う代わりに、 +小さな(3列、5行)一般的なものを作成する。 再現可能な +例の書き方については、Hadley +Wickhamによるこの記事を参照のこと。 + +オブジェクトを他の人と共有するには、それが比較的小さければ、 +、関数 `dput()` を使うことができる。 +、メモリ上のオブジェクトとまったく同じオブジェクトを再作成するために使用できるRコードが出力される: + +```{r, results="show", purl=TRUE} +## irisはRに付属するデータフレームの例であり、 head()はデータフレームの最初の部分を返す +## 関数である +dput(head(iris)) +``` + +オブジェクトのサイズが大きい場合は、生ファイル(つまり、CSV +ファイル)と、エラーが発生した時点までのスクリプト(およびの問題に関係ないものをすべて削除した後のファイル)を提供してください。 あるいは、特にあなたの質問が +データフレームに関連していない場合は、任意のRオブジェクトをファイルに保存することができます[^export]: + +```{r, eval=FALSE, purl=FALSE} +saveRDS(iris, file="/tmp/iris.rds") +``` + +しかし、このファイルの内容は人間が読めるものではないので、 +Stack Overflowに直接投稿することはできません。 その代わりに、 +。その人は`readRDS()`コマンドでそのファイルを読むことができます(ここでは、 +、ダウンロードされたファイルは +、そのユーザーのホームディレクトリの`Downloads`フォルダにあると仮定しています): + +```{r, eval=FALSE, purl=FALSE} +some_data <- readRDS(file="~/Downloads/iris.rds") +``` + +最後になりますが、**必ず`sessionInfo()`** +の出力を含めるようにしてください。プラットフォーム、使用しているRと +パッケージのバージョン、その他問題を理解するのに非常に役立つ情報を提供してくれるからです。 + +```{r, results="show", purl=TRUE} +sessionInfo() +``` + +### どこに助けを求めればいいのか? + +- コース中、あなたの隣に座っている人。 + 、ワークショップ中に隣の人と話し、自分の答えを比較し、 + 、助けを求めることをためらわないでください。 +- 友好的な同僚:もしあなたより経験豊富な人を知っていれば、 + 、あなたを助けてくれるかもしれない。 +- [Stack Overflow](https://stackoverflow.com/questions/tagged/r): + あなたの質問が過去に回答されたことがなく、よく練られたものであれば、 + 5分以内に回答が得られる可能性があります。 + How to ask good + questionのガイドラインに従うことを忘れずに。 +- R-helpメーリングリスト + ](https://stat.ethz.ch/mailman/listinfo/r-help): + 多くの人に読まれていて(Rコアチームのほとんどを含む)、多くの人が + 投稿していますが、口調はかなり辛口で、 + 新しいユーザーを必ずしも歓迎しているとは限りません。 あなたの質問が正当なものであれば、 + 、すぐに回答が返ってくる可能性が高いが、 + 、スマイルマーク付きで返ってくるとは思わないこと。 また、ここでは他のどこよりも、 + 正しい語彙を使うようにしましょう(そうしないと、 + の質問に答えるのではなく、 + あなたの言葉の誤用を指摘する答えが返ってくるかもしれません)。 また、質問内容が特定のパッケージではなく、 + ベースとなる関数に関するものであれば、より成功しやすいでしょう。 +- 質問が特定のパッケージに関するものであれば、そのパッケージのメーリングリスト( + )があるかどうか確認してください。 通常は + `packageDescription("name-of-package")` を使ってアクセスできるパッケージのDESCRIPTIONファイル + に含まれています。 また、 + そのパッケージの作者に直接メールを送ってみたり、 + コードリポジトリ(例:GitHub)にissueを開いてみるのもよいだろう。 +- また、トピックに特化したメーリングリスト(GIS、 + 系統遺伝学など)もある。全リストは + [こちら](https://www.r-project.org/mail.html)。 + +### その他のリソース + +- Rメーリングリストの[投稿ガイド](https://www.r-project.org/posting-guide.html)。 + +- How to ask for R + help + 役立つガイドライン。 + +- Jon + Skeetによるこのブログ記事 + プログラミングの質問の仕方について、かなり包括的なアドバイスがある。 + +- reprex](https://cran.rstudio.com/web/packages/reprex/)パッケージ + は、 + ヘルプを求めるときに、再現可能な例を作成するのに非常に役立ちます。 + rOpenSciコミュニティコール "How to ask questions so they get answered" (Github + link and video + recording) には、 + reprexパッケージとその哲学のプレゼンテーションが含まれています。 + +## Rパッケージ + +### 荷物の積み込み + +上で見てきたように、RパッケージはRの基本的な役割を担っている。 +、パッケージがインストールされていることを前提に、パッケージの機能を利用する。 +、それを利用できるようにするには、まずパッケージをロードする必要がある。 これは +`library()`関数で行う。 以下に `ggplot2` をロードする。 + +```{r loadp, eval=FALSE, purl=TRUE} +library("ggplot2") +``` + +### パッケージのインストール + +デフォルトのパッケージリポジトリは The _Comprehensive R Archive +Network_ (CRAN) で、CRAN で利用可能なパッケージは `install.packages()` 関数で +インストールできます。 例えば、 +、後で説明する `dplyr` パッケージをインストールする。 + +```{r craninstall, eval=FALSE, purl=TRUE} +install.packages("dplyr") +``` + +このコマンドは、`dplyr` パッケージと、その +依存パッケージ、つまり、そのパッケージが機能するために依存しているすべてのパッケージをインストールします。 + +もう一つの主要なRパッケージのリポジトリは、Bioconductorによって管理されている。 [Bioconductorパッケージ](https://bioconductor.org/packages/release/BiocViews.html#___Software) は、専用のパッケージ、 +すなわち `BiocManager` を使用して管理およびインストールされます。 + +```{r, eval=FALSE, purl=TRUE} +install.packages("BiocManager") +``` + +SummarizedExperiment`(後で +)、`DESeq2`(RNA-Seq解析用)、その他BioconductorやCRANにあるパッケージは、`BiocManager::install\`で +。 + +```{r, eval=FALSE, purl=TRUE} +BiocManager::install("SummarizedExperiment") +BiocManager::install("DESeq2") +``` + +デフォルトでは、`BiocManager::install()` はインストールされているすべてのパッケージをチェックし、新しいバージョンがあるかどうかも確認します。 もしあれば、それが表示され、「すべて/いくつか/なしを更新しますか? [a/s/n]:\`、そしてあなたの答えを待つ。 パッケージのバージョンは最新のものを用意するよう努力すべきですが、実際には、パッケージがロードされる前の新鮮なRセッションでのみパッケージを更新することをお勧めします。 + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- RとRStudioを使い始める + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/ja/episodes/23-starting-with-r.Rmd b/locale/ja/episodes/23-starting-with-r.Rmd new file mode 100644 index 000000000..758b39d60 --- /dev/null +++ b/locale/ja/episodes/23-starting-with-r.Rmd @@ -0,0 +1,921 @@ +--- +source: Rmd +title: R の紹介 +teaching: 60 +exercises: 60 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- R に関連する次の用語を定義します: オブジェクト、代入、呼び出し、関数、引数、オプション。 +- R のオブジェクトに値を割り当てます。 +- オブジェクトに _名前を付ける_方法を学ぶ +- コメントを使用してスクリプトに情報を与えます。 +- R で単純な算術演算を解きます。 +- 関数を呼び出し、引数を使用してデフォルトのオプションを変更します。 +- ベクトルの内容を検査し、その内容を操作します。 +- ベクトルから値をサブセット化して抽出します。 +- データが欠落しているベクトルを解析します。 + +:::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- R の最初のコマンド + +:::::::::::::::::::::::::::::::::::::::::::::: + +> This episode is based on the Data Carpentries's _Data Analysis and +> Visualisation in R for Ecologists_ lesson. + +## R でオブジェクトを作成する + +コンソールに math と入力するだけで、R から出力を取得できます。 + +```{r, purl=TRUE} +3 + 5 +12 / 7 +``` + +ただし、便利で興味深いことを行うには、_値_を +_オブジェクト_ に割り当てる必要があります。 オブジェクトを作成するには、オブジェクトに名前を付け、その後に +代入演算子 `<-` と、それに付けたい値を付ける必要があります。 + +```{r, purl=TRUE} +weight_kg <- 55 +``` + +`<-` は代入演算子です。 右側の値を左側の +個のオブジェクトに割り当てます。 したがって、「x <- 3」を実行すると、「x」の値は +`3` になります。 矢印は 3 **が `x` に入る** と読むことができます。 歴史的 +理由により、代入に `=` を使用することもできますが、 +のコンテキストで使用できるわけではありません。 構文に +わずかな違い](https://blog.revolutionanalytics.com/2008/12/use-equals-or-arrow-for-assignment.html) +があるため、常に `< を使用することをお勧めします。 -` 割り当て用。 + +RStudio では、 オプション を入力しながら、 Alt + \- を入力すると ( \- キーと同時に Alt +を押すと)、PC で +1 回のキーストロークで `<-` が書き込まれます。 + \- ( オプション \- キーと同時に押す) は、Mac でも +と同じことを行います。 + +### 変数に名前を付ける + +オブジェクトには、「x」、「current_temperature」、または「subject_id」などの任意 +名前を付けることができます。 オブジェクト名は明示的で、長 +ないようにしたいと考えています。 数字で始めることはできません (「2x」は無効ですが、「x2」 +は有効です)。 R では大文字と小文字が区別されます (たとえば、`weight_kg` は +の `Weight_kg` とは異なります)。 R の基本的な関数の名前であるため、使用でき +名前が +かあります (例: `if`、`else`、 +`for`。2 [こちら](https://stat.ethz.ch)を参照)完全なリストについては、/R-manual/R-devel/library/base/html/Reserved.html) +)。 一般に、たとえ許可されていても、他の関数名 (例: `c`、`T`、`mean`、`data`、`df`、 +`weights`) は使用しないことが +です。 疑問がある場合は、ヘルプを参照して、その名前がすでに +で使用されているかどうかを確認してください。 また +`my.dataset` のように、オブジェクト名内にドット (`.`) を使用しないことも最善です。 R には歴史的な理由から名前にドットが含まれる関数が多数あります +が、R +(メソッド) や他のプログラミング言語ではドットが特別な意味を持っているため、ドットは避けるのが最善です +。 オブジェクト名には名詞を使用し、関数名には動詞 +を使用することもお勧めします。 +のスタイル (スペースを入れる場所、オブジェクトの名前など) に一貫性を持たせることが重要です。 +コーディング スタイルを使用すると、 +の自分や共同作業者にとって、コードがより明確に読みやすくなります。 R では、人気のあるスタイル ガイド +には、[Google の](https://google.github.io/styleguide/Rguide.xml)、 +[tidyverse の](https://style.tidyverse.org/) スタイル、およびBioconductor +スタイル +ガイド。 +Tidyverse は非常に包括的であり、最初は +では圧倒されるように思えるかもしれません。 +[**`lintr`**](https://github.com/jimhester/lintr) パッケージを +にインストールすると、コードのスタイルの問題が自動的にチェックされます。 + +> **オブジェクトと変数**: 「R」で「オブジェクト」として知られているものは、他の多くのプログラミング言語では「変数」として知られて +> ます。 +> に応じて、「オブジェクト」と「変数」は +> に異なる意味を持つ可能性があります。 ただし、このレッスンでは、2 つの単語は +> 的に使用されます。 詳細については、 +> [ここを参照してください。](https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Objects) + +オブジェクトに値を割り当てるとき、R は何も出力しません。 かっこを使用するか +名を入力することで、 +に値を強制的に出力させることができます。 + +```{r, purl=TRUE} +weight_kg <- 55 # 何も出力しません +(weight_kg <- 55) # しかし、呼び出しを括弧で囲むと `weight_kg` の値が出力され、 +weight_kg # オブジェクトの名前を入力しても同様に出力されます +``` + +R のメモリに「weight_kg」があるので、それを使って算術演算を行うことができます。 +、この重量をポンドに変換したい場合があります (ポンドでの重量は kg での重量の 2.2 倍です)。 + +```{r, purl=TRUE} +2.2 * weight_kg +``` + +オブジェクトに新しい値を割り当てることで、オブジェクトの値を変更することもできます。 + +```{r, purl=TRUE} +weight_kg <- 57.5 +2.2 * weight_kg +``` + +これは、 +つのオブジェクトに値を割り当てても、他のオブジェクトの値は変更されないことを意味します。たとえば、動物の体重をポンド単位で新しい +オブジェクト `weight_lb` に保存してみましょう。 + +```{r, purl=TRUE} +weight_lb <- 2.2 * weight_kg +``` + +次に「weight_kg」を 100 に変更します。 + +```{r} +weight_kg <- 100 +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ: + +オブジェクト「weight_lb」の現在の内容は何だと思いますか? +126\.5 それとも 220? + +:::::::::::::::::::::::::::::::::::::::::::::: + +## コメント + +のコメント文字は `#` です。0 スクリプトの `#` の右側にあるものはすべて R によって無視されます。スクリプトにメモ +説明を残すと便利です。 + +RStudio では、段落のコメントまたはコメント解除が簡単に行えます。 +コメントしたい行を選択した後、 +キーボード Ctrl + Shift + Cを同時に押します。 +の場合、1 行だけをコメントアウトしたい場合は、その行の任意 +位置にカーソルを置きます (つまり、行全体を選択する必要はありません)。その後 +Ctrl + Shift + C押します。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ + +次の各ステートメントの後の値は何ですか? + +```{r, purl=TRUE} +mass <- 47.5 # 質量? +age <- 122 # 年齢? +mass <- mass * 2.0 # 質量? +age <- age - 20 # 年齢? +mass_index <- mass/age # 質量指数? +``` + +:::::::::::::::::::::::::::::::::::::::::::::: + +## 関数とその引数 + +関数は、操作の割り当て +を含む、より複雑なコマンド セットを自動化する「定型スクリプト」です。 多くの関数は事前定義されているか、R _パッケージ_ をインポートすることで +可能になります (詳細は後ほど)。 関数 +は通常、_arguments_ と呼ばれる 1 つ以上の入力を取得します。 関数は多くの場合 (常に +ではありませんが) _値_ を返します。 典型的な例は関数 `sqrt()` です。 +入力 (引数) は数値でなければならず、戻り値 (実際には +出力) はその数値の平方根です。 関数の実行 (「実行中」) +は関数の _呼び出し_ と呼ばれます。 関数呼び出しの例は次のとおりです。 + +```{r, eval=FALSE, purl=FALSE} +b <- sqrt(a) +``` + +ここでは、`a` の値が `sqrt()` 関数に与えられ、`sqrt()` 関数は +平方根を計算し、その値をオブジェクト \` +に代入して返します。 この関数は引数を 1 つだけ取るため、非常に単純です。 + +関数の戻り値「値」は数値 (`sqrt()` のような) である必要はなく、 +である必要もありません。また、単一の項目である必要もありません。一連のものや +、さらにはデータセットでも構いません。 データ ファイルを R に読み込むと、それがわかります。 + +引数には、数値やファイル名だけでなく、他の +も含めることができます。 各引数の正確な意味は関数ごとに異なるため、ドキュメントで調べて +にする必要があります (下記を参照)。 一部の関数は引数を取ります +はユーザーによって指定されるか、指定されなかった場合は _デフォルト_ 値を取ります: +これらは _オプション_ と呼ばれます。 オプションは通常、「不正な値」を無視するかどうか、プロットでどのような記号を使用 +かなど、 +関数の動作方法を変更するために使用されます。 ただし、特定の値が必要な場合は、デフォルトの代わりに使用される値 +を選択して指定できます。 + +複数の引数を取ることができる関数 `round()` を試してみましょう。 + +```{r, results="show", purl=TRUE} +round(3.14159) +``` + +ここでは、1 つの引数 `3.14159` を指定して `round()` を呼び出しましたが、 +が値 `3` を返しました。 これは、デフォルトでは最も近い +整数に丸められるためです。 さらに多くの桁が必要な場合は、「round」関数に関する +情報を取得することでその方法がわかります。 `args(round)` を使用するか、`?round` を使用して +関数のヘルプを参照することができます。 + +```{r, results="show", purl=TRUE} +args(round) +``` + +```{r, eval=FALSE, purl=TRUE} +?round +``` + +別の桁数が必要な場合は、`digits=2` または必要な桁数を入力 +ことがわかります。 + +```{r, results="show", purl=TRUE} +round(3.14159, digits = 2) +``` + +定義されているのとまったく同じ順序で引数を指定する場合は +に名前を付ける必要はありません。 + +```{r, results="show", purl=TRUE} +round(3.14159, 2) +``` + +引数に名前を付けた場合は、その順序を入れ替えることができます。 + +```{r, results="show", purl=TRUE} +round(digits = 2, x = 3.14159) +``` + +関数呼び出しの最初にオプションではない引数 ( +四捨五入する数値など) を置き、すべてのオプションの +引数の名前を指定することをお勧めします。 そうしないと、コードを読む人が、 +をしているのかを理解するために、なじみのない引数を持つ関数の定義を調べなければなら +可能性があります。 引数の名前を指定することで、関数インターフェースの将来の変更 (既存の引数の間に +引数が追加される可能性) から +することもできます。 + +## ベクトルとデータ型 + +ベクトルは R で最も一般的かつ基本的なデータ型であり、ほぼ R の主力である +です。ベクトルは、 +数字や文字などの一連の値で構成されます。 +の `c()` 関数を使用して、一連の値をベクトルに割り当てることができます。 たとえば、動物の体重のベクトルを作成し、それを新しいオブジェクト `weight_g` に +に割り当てることができます。 + +```{r, purl=TRUE} +weight_g <- c(50, 60, 65, 82) +weight_g +``` + +ベクトルには文字も含めることができます。 + +```{r, purl=TRUE} +molecules <- c("dna", "rna", "protein") +molecules +``` + +ここでは「dna」や「rna」などの引用符が重要です。 引用符 +がないと、R は `dna`、`rna`、および +`protein` と呼ばれるオブジェクトがあると想定します。 これらのオブジェクトは R のメモリに存在しないため、エラー メッセージが +されます。 + +ベクトルの内容を検査できる関数が多数あります。 `length()` は、特定のベクトルに含まれる要素の数を示します。 + +```{r, purl=TRUE} +length(weight_g) +length(molecules) +``` + +ベクトルの重要な特徴は、すべての要素が +タイプのデータであることです。 関数 `class()` は、オブジェクトのクラス ( +型の要素) を示します。 + +```{r, purl=TRUE} +class(weight_g) +class(molecules) +``` + +関数 `str()` は、 +オブジェクトとその要素の構造の概要を提供します。 これは、 +て複雑なオブジェクトを扱う場合に便利な関数です。 + +```{r, purl=TRUE} +str(weight_g) +str(molecules) +``` + +`c()` 関数を使用して、ベクトルに他の要素を追加できます。 + +```{r} +weight_g <- c(weight_g, 90) # ベクトルの最後に追加 +weight_g <- c(30, weight_g) # ベクトルの先頭に追加 +weight_g +``` + +最初の行では、元のベクトル `weight_g` を取得し、その末尾に +値 `90` を追加し、結果を +`weight_g` に保存します。 次に、値 `30` を先頭に追加し、結果を再び +として `weight_g` に保存します。 + +これを何度も繰り返してベクトルを成長させたり、 +データセットを組み立てたりすることができます。 これは、プログラムするときに、 +または計算している結果を追加するのに役立つ場合があります。 + +**アトミック ベクトル**は最も単純な R **データ型**であり、単一型の線形 +ベクトルです。 上では、R が使用する 6 つの主な **アトミック +ベクトル** タイプのうち 2 つ、つまり `"character"` と `"numeric"` (または +`"double"`) を見てきました。 これらは、すべての R オブジェクト +が構築される基本的な構成要素です。 他の 4 つの **原子ベクトル** タイプは次のとおりです。 + +- `TRUE` および `FALSE` の場合は `"logical"` (ブール データ型) +- 整数の場合は `"integer"` (たとえば、`2L`、`L` は R + にそれが整数であることを示します) +- `"complex"` は、実数と虚数の + 部分を持つ複素数を表します (例: 1 + 4i)。これについて説明するのはこれですべてです。 +- ビットストリームの「raw」\` (これ以上は説明しません) + +`typeof()` 関数 +を使用し、ベクトルを引数として入力することで、ベクトルの型をチェックできます。 + +ベクトルは、R が使用する多くの **データ構造** の 1 つです。 その他 +重要なものは、リスト (`list`)、行列 (`matrix`)、データ フレーム +(`data.frame`)、因子 (`factor`)、および配列 (`array`) です。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ: + +アトミック ベクトルの型は、文字、数値 (または +double)、整数、および論理型であることがわかりました。 しかし、これらのタイプを +つのベクトルに混在させようとするとどうなるでしょうか? + +::::::::::::::: solution + +## 解決 + +R はそれらをすべて同じ型に暗黙的に変換します。 + +:::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ: + +これらのそれぞれの例では何が起こるでしょうか? (ヒント: `class()` を使用してオブジェクトのデータ型を確認 +、名前を入力して何が起こるかを確認します): + +```{r, eval=TRUE} +num_char <- c(1, 2, 3, "a") +num_logical <- c(1, 2, 3, TRUE, FALSE) +char_logical <- c("a", "b", "c", TRUE) +tricky <- c(1, 2, 3, "4") +``` + +::::::::::::::: solution + +## 解決 + +```{r, purl=TRUE} +class(num_char) +num_char +class(num_logical) +num_logical +class(char_logical) +char_logical +class(tricky) +tricky +``` + +:::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ: + +なぜそれが起こると思いますか? + +::::::::::::::: solution + +## 解決 + +ベクトルのデータ型は 1 つだけです。 R は、 +が情報を失わないという _共通分母_ を見つけるために、このベクトルの内容を +に変換 (強制) しようとします。 + +:::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ: + +次の例では、`combined_logical` 内の `"TRUE"` (文字として) +となる値はいくつありますか。 + +```{r, eval=TRUE} +num_logical <- c(1, 2, 3, TRUE) +char_logical <- c("a", "b", "c", TRUE) +combined_logical <- c(num_logical, char_logical) +``` + +::::::::::::::: solution + +## 解決 + +唯一。 過去のデータ型の記憶はなく、ベクトルが初めて評価されるときに強制 +が発生します。 したがって、「num_logical」の「TRUE」 +「combined_logical」で +「1」に変換される前に、「1」に変換されます。 + +```{r} +combined_logical +``` + +:::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ: + +R では、オブジェクトをあるクラスから別のクラスに変換することを +強制\* と呼びます。 これらの変換は階層 +に従って行われ、一部の型が優先的に他の型に強制されます。 これらのデータ +がどのように強制されるかの階層を表す図を描いてもらえます +? + +::::::::::::::: solution + +## 解決 + +論理 → 数値 → 文字 ← 論理 + +:::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::: + +```{r, echo=FALSE, eval=FALSE, purl=TRUE} +## アトミックベクトルは文字型、数値型、整数型、 +## 論理型があることを見てきました。しかし、これらの型を1つの +## ベクトルに混在させようとしたらどうなるでしょうか? + +## それぞれの例で何が起こるか?(ヒント: `class()` を使って +## オブジェクトのデータ型をチェックしてみましょう) +num_char <- c(1, 2, 3, "a") + +num_logical <- c(1, 2, 3, TRUE) + +char_logical <- c("a", "b", "c", TRUE) + +tricky <- c(1, 2, 3, "4") + +## なぜそうなると思いますか? + +## +## ベクトル内で、異なる型のオブジェクトが単一の共有型に変換されることにお気づきでしょう。Rでは、 +## オブジェクトをあるクラスから別のクラスに変換することを +## _coercion_と呼んでいます。これらの変換は階層に従って行われ、 +## ある型が優先的に他の型に強制されます。 +## これらのデータ型がどのように強制されるのか、その階層を表す図を描けますか? +``` + +## ベクトルのサブセット化 + +ベクトルから 1 つまたは複数の値を抽出したい場合は、角括弧内に 1 つまたは複数のインデックスを指定する必要が +ます。 例えば: + +```{r, results="show", purl=TRUE} +molecules <- c("dna", "rna", "peptide", "protein") +molecules[2] +molecules[c(3, 2)] +``` + +インデックスを繰り返して、元のオブジェクトよりも要素 +が多いオブジェクトを作成することもできます。 + +```{r, results="show", purl=TRUE} +more_molecules <- molecules[c(1, 2, 3, 2, 1, 4)] +more_molecules +``` + +R インデックスは 1 から始まります。 Fortran、MATLAB、 +Julia、R などのプログラミング言語は +から数え始めます。これは人間が通常行うことだからです。 C ファミリの言語 (C++、Java、Perl、 +、Python を含む) は 0 からカウントします。これは、コンピュータにとってその方が簡単なためです。 + +最後に、負のインデックスを使用して、指定された一部の要素を除くベクトル +のすべての要素を取得することもできます。 + +```{r} +分子 ## すべての分子 +分子[-1] ## 最初の分子を除くすべての分子 +分子[-c(1, 3)] ## 1 番目/3 番目の分子を除くすべての分子 +分子[c(-1, -3)] # # 1番目/3番目を除くすべて +``` + +## 条件付きサブセット化 + +サブセット化のもう 1 つの一般的な方法は、論理ベクトルを使用することです。 `TRUE` は同じインデックスを持つ要素を選択し +が、`FALSE` は選択しません。 + +```{r, purl=TRUE} +weight_g <- c(21, 34, 39, 54, 55) +weight_g[c(TRUE, FALSE, TRUE, TRUE, FALSE)] +``` + +通常、これらの論理ベクトルは手動で入力されるのではなく、他の関数または論理テストの +出力です。 たとえば、50 を超える値のみを選択したい場合は、 +のようにします。 + +```{r, purl=TRUE} +## will return logicals with TRUE for the indices that meet +## the condition +weight_g > 50 +## so we can use this to select only the values above 50 +weight_g[weight_g > 50] +``` + +`&` (両方の条件が true、 +AND) または `|` (少なくとも 1 つの条件が true、OR) を使用して複数のテストを結合できます。 + +```{r, results="show", purl=TRUE} +weight_g[weight_g < 30 | weight_g > 50] +weight_g[weight_g >= 30 & weight_g == 21] +``` + +ここで、「<」は「より小さい」、「>」は「より大きい」、「>=」は +「以上」、「==」は「等しい」を表します。 2 つの等号 +記号「==」は、左側と +の数値が等しいかどうかをテストするものであり、(「<-」と同様に) 変数の代入を +する単一の `=` 記号と混同しないでください。 。 + +一般的なタスクは、ベクトル内の特定の文字列を検索することです。\ +「or」演算子 `|` を使用して複数の値が等しいかどうかをテストすることもできますが、 +これはすぐに面倒になります。 関数 `%in%` を使用すると、検索ベクトルの要素が見つかったかどうかを +できます。 + +```{r, purl=TRUE} +分子 <- c("dna", "rna", "タンパク質", "ペプチド") +分子[分子 == "rna" |分子 == "dna"] # rna と dna の両方を返します +分子 %in% c("rna", "dna", "代謝物", "ペプチド", "グリセロール") +分子[分子 %in% c("rna", " 「DNA」、「代謝物」、「ペプチド」、「グリセロール」)] +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ: + +なぜ `"four" > "five"` が `TRUE` を返すのか理解できますか? + +::::::::::::::: solution + +## 解決 + +```{r} +"four" > "five" +``` + +文字列で `>` または `<` を使用すると、R はそれらのアルファベット順を比較します。 +ここで、`"four"` は `"five"` の後に来るので、それは \* +より大きい\* です。 + +:::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::: + +## 名前 + +ベクトルの各要素に名前を付けることができます。 +より下のコード チャンクは、名前のない初期ベクトル、名前の設定方法、および +取得される様子を示しています。 + +```{r} +x <- c(1, 5, 3, 5, 10) +names(x) ## 名前なし +names(x) <- c("A", "B", "C", "D", " E") +名前(x) ## これで名前が決まりました +``` + +ベクトルに名前がある場合、 +に加えて名前によって要素にアクセスすることができます。 + +```{r} +x[c(1, 3)] +x[c("A", "C")] +``` + +## データが欠落しています + +R はデータセットを分析するように設計されているため、欠損データが +であるという概念が含まれています (これは +のプログラミング言語では一般的ではありません)。 欠損データはベクトルで「NA」として表されます。 + +数値の演算を行う場合、扱っているデータに欠損値が含まれている場合 +ほとんどの関数は「NA」を返します。 この機能により、 +データを処理し +いるケースを見逃しにくくなります。 引数 `na.rm = TRUE` を追加すると、欠損値を無視して結果を +として計算できます。 + +```{r} +heights <- c(2, 4, 4, NA, 6) +mean(heights) +max(heights) +mean(heights, na.rm = TRUE) +max(heights, na.rm = TRUE) +``` + +データに欠損値が含まれている場合は、関数 `is.na()`、`na.omit()`、および `complete.cases()` に +ておくとよいでしょう。 例については、以下の +を参照してください。 + +```{r} +## 欠損値のない要素を抽出します。 +heights[!is.na(heights)] + +## 不完全なケースを削除したオブジェクトを返します。 +## 返されるオブジェクトは、タイプ `"numeric"` の原子ベクトルです。 +## (または `"double"`)。 +na.omit(heights) + +## 完全なケースである要素を抽出します。 +## 返されるオブジェクトは、タイプ `"numeric"` の原子ベクトルです。 +## (または `"double"`)。 +の高さ[完全なケース(高さ)] +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ: + +1. このインチ単位の高さのベクトルを使用して、NA を削除した新しいベクトルを作成します。 + +```{r} +高さ <- c(63, 69, 60, 65, NA, 68, 61, 70, 61, 59, 64, 69, 63, 63, NA, 72, 65, 64, 70, 63, 65) +``` + +2. 関数 `median()` を使用して、`heights` ベクトルの中央値を計算します。 +3. R を使用して、セット内の身長が 67 インチを超える人が何人いるかを計算します。 + +::::::::::::::: solution + +## 解決 + +```{r, purl=TRUE} +heights_no_na <- heights[!is.na(heights)] +## または +heights_no_na <- na.omit(heights) +``` + +```{r, purl=TRUE} +median(heights, na.rm = TRUE) +``` + +```{r, purl=TRUE} +height_above_67 <- height_no_na[heights_no_na > 67] +長さ(heights_above_67) +``` + +:::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::: + +## ベクトル {#sec:genvec}の生成 + +```{r, echo=FALSE} +set.seed(1) +``` + +### コンストラクター + +異なるタイプのベクトルを生成する関数がいくつか存在します。 数値のベクトルを生成 +には、`numeric()` +コンストラクターを使用し、出力ベクトルの長さを +パラメーターとして指定します。 値は 0 で初期化されます。 + +```{r, purl=TRUE} +数値(3) +数値(10) +``` + +長さ 0 の数値ベクトルを要求すると、次のように +が得られることに注意してください。 + +```{r, purl=TRUE} +数値(0) +``` + +文字と論理に対しても同様のコンストラクターがあり、 +`character()` と `logical()` という名前が付けられます。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ: + +文字ベクトルと論理ベクトルのデフォルトは何ですか? + +::::::::::::::: solution + +## 解決 + +```{r, purl=TRUE} +文字(2) ## 空の文字 +論理的(2) ## FALSE +``` + +:::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::: + +### 要素を複製する + +`rep` 関数を使用すると、値を特定の回数 ( +回) 繰り返すことができます。 たとえば、長さ 5 の数値ベクトルを +から値 -1 で開始したい場合は、次のようにすることができます。 + +```{r, purl=TRUE} +担当者(-1, 5) +``` + +同様に、収集されるデータ +に仮定を設定せずに、欠損値が入力されたベクトルを生成するには (多くの場合、 +から始めるのが良い方法です): + +```{r, purl=TRUE} +担当者(NA, 5) +``` + +`rep` は、入力として任意の長さのベクトル (上記では長さ 1 のベクトル +を使用しました) および任意のタイプを受け取ることができます。 たとえば、 +値 1、2、3 を 5 回繰り返す場合は、次のようにします。 + +```{r, purl=TRUE} +rep(c(1, 2, 3), 5) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ: + +値 1、2、3 を 5 回繰り返したいのに、 +1 を 5 つ、2 を 5 つ、3 を 5 つこの順序で取得した場合はどうなるでしょうか。 +可能性は 2 つあります。ヘルプについては `?rep` または `?sort` を参照してください。 + +::::::::::::::: solution + +## 解決 + +```{r, purl=TRUE} +rep(c(1, 2, 3), each = 5) +sort(rep(c(1, 2, 3), 5)) +``` + +:::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::: + +### シーケンスの生成 + +もう 1 つの非常に便利な関数は、 +の数値シーケンスを生成する `seq` です。 たとえば、1 から 20 +までの整数のシーケンスを 2 ずつ生成するには、次のコマンドを使用します。 + +```{r, purl=TRUE} +seq(from = 1, to = 20, by = 2) +``` + +`by` のデフォルト値は 1 で、1 のステップで 1 つの値から別の値への +シーケンスの生成が頻繁に使用されることを考えると、 +というショートカットがあります。 + +```{r, purl=TRUE} +seq(1, 5, 1) +seq(1, 5) ## default by +1:5 +``` + +最終長さが +の 1 から 20 までの一連の数値を生成するには、次のコマンドを使用します。 + +```{r, purl=TRUE} +seq(from = 1, to = 20, length.out = 3) +``` + +### ランダムなサンプルと順列 + +有用な関数の最後のグループは、ランダムな +データを生成する関数です。 最初の `sample` は、 +のベクトルのランダムな置換を生成します。 たとえば、口頭試験を行わない +人の生徒にランダムな順序を付けるには +まず各生徒に 1 から 10 までの番号を割り当てます (たとえば、名前のアルファベット順に基づきます)。次に次のようにします。 + +```{r, purl=TRUE} +sample(1:10) +``` + +さらなる引数がなければ、`sample` はベクトルのすべての +要素の順列を返します。 特定のサイズのランダムなサンプルが必要な場合、I +はこの値を 2 番目の引数として設定します。 以下では、事前定義された `letters` ベクトルに含まれるアルファベットから 5 つのランダムな +文字をサンプリングします。 + +```{r, purl=TRUE} +sample(letters, 5) +``` + +入力ベクトルよりも大きな出力が必要な場合、または一部の要素を複数回 +できるようにしたい場合は、引数 `replace` +を `TRUE` に設定する必要があります。 + +```{r, purl=TRUE} +sample(1:5, 10, replace = TRUE) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ: + +上記の関数を試してみると、 +サンプルは実際にランダムであり、同じ +順列が 2 回発生することはないことがわかるでしょう。 これらのランダムな描画を再現できるようにするには、ランダム サンプルを描画する前に +`set.seed()` を使用 +て乱数生成シードを手動で設定します。 + +近所の人と一緒にこの機能をテストしてください。 まず、「1:10」のランダムな +順列を 2 つ個別に描画し、 +の異なる結果が得られることを観察します。 + +次に、たとえば `set.seed(123)` でシードを設定し、 +ランダムな描画を繰り返します。 同じランダムな抽選が行われることに注目してください。 + +別のシードを設定して繰り返します。 + +::::::::::::::: solution + +## 解決 + +さまざまな順列 + +```{r, purl=TRUE} +sample(1:10) +sample(1:10) +``` + +シード 123 と同じ順列 + +```{r, purl=TRUE} +set.seed(123) +sample(1:10) +set.seed(123) +sample(1:10) +``` + +違う種 + +```{r, purl=TRUE} +set.seed(1) +sample(1:10) +set.seed(1) +sample(1:10) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +### 正規分布からサンプルを抽出する + +最後に説明する関数は `rnorm` で、正規分布からランダムな +サンプルを抽出します。 平均 +および 100、標準偏差 1 および 5 の 2 つの正規分布 (_N(0, 1)_ および +_N(100, 5)_ と表記) を以下に示します。 + +```{r, echo=FALSE, fig.width=12, fig.height=6, fig.cap="Two normal distributions: *N(0, 1)* on the left and *N(100, 5)* on the right."} +par(mfrow = c(1, 2)) +plot(density(rnorm(1000)), main = "", sub = "N(0, 1)") +plot(density(rnorm(1000, 100, 5)), main = "", sub = "N(100, 5)") +``` + +3 つの引数「n」、「mean」、「sd」は、サンプル +のサイズと、正規分布のパラメーター、つまり平均 +とその標準偏差を定義します。 後者のデフォルトは 0 と 1 です。 + +```{r, purl=TRUE} +rnorm(5) +rnorm(5, 2, 2) +rnorm(5, 100, 5) +``` + +スクリプトの書き方と +のデータ構造の基本を学習したので、より大きなデータの操作を開始する準備が整い、データ フレームについて +します。 + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Rと対話する方法 + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/ja/episodes/25-starting-with-data.Rmd b/locale/ja/episodes/25-starting-with-data.Rmd new file mode 100644 index 000000000..eb3277e5c --- /dev/null +++ b/locale/ja/episodes/25-starting-with-data.Rmd @@ -0,0 +1,774 @@ +--- +source: Rmd +title: データから始める +teaching: 30 +exercises: 30 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- `data.frame` が何なのか説明してみましょう。 +- .csv ファイルからデータ フレームに外部データを読み込みましょう。 +- データフレームの内容を要約してみましょう。 +- ファクターとは何か? +- string と factor を変換してみましょう。 +- factor の並び替えとリネームを行ってみましょう。 +- 日付をフォーマットしてみましょう。 +- データをエクスポートして保存してみましょう。 + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- Rによる最初のデータ分析 + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +> このエピソードは、Data Carpentriesの_Data Analysis and +> Visualisation in R for Ecologists_レッスンに基づいています。 + +## 遺伝子発現データのプレゼンテーション + +Blackmore _et al._ +(2017)](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5544260/), _The +effect of upper-respiratory infection on transcriptomic changes in +CNS_ によって発表されたデータの一部を使用する予定である。 研究の目的は、 +上部呼吸器感染症が、感染後の小脳と脊髄で +起こるRNA転写の変化に及ぼす影響を調べることであった。 性別を一致させた8匹の +週齢のC57BL/6マウスに、生理食塩水または +鼻腔内経路でインフルエンザAを接種し、0日目 +(非感染)、4日目、8日目に小脳と +脊髄組織におけるトランスクリプトーム変化をRNA-seqで評価した。 + +データセットは、カンマ区切りの値(CSV)ファイルとして保存される。 各行 +は1つのRNA発現測定の情報を持ち、最初の11列 +はそれを表している: + +| コラム | 説明 | +| ---- | ---------------------------------------- | +| 遺伝子 | 測定された遺伝子名 | +| サンプル | 遺伝子発現を測定したサンプル名 | +| 表現 | 遺伝子発現の値 | +| 有機体 | 生物/種 - ここではすべてのデータはマウスに由来する | +| 年齢 | マウスの年齢(ここではすべてのマウスが8週齢であった) | +| セックス | マウスの性別 | +| 感染症 | マウスの感染状態、すなわちA型インフルエンザに感染しているか、感染していないか。 | +| 緊張 | インフルエンザA型。 | +| 時間 | 感染期間(日単位)。 | +| 組織 | 遺伝子発現実験に使用した組織、すなわち小脳または脊髄。 | +| マウス | マウス固有の識別子。 | + +R関数の`download.file()`を使って遺伝子発現データを含む +CSVファイルをダウンロードし、 +`read.csv()` を使ってCSVファイルの内容を +`data.frame`クラスのオブジェクトとしてメモリにロードする。 download.file`コマンドの内部では、 +の最初のエントリーは、ソースURLの文字列である。 このソースURL +はGitHubリポジトリからCSVファイルをダウンロードします。 +、カンマ(`"data/rnaseq.csv"`)の後のテキストは、 +、ローカルマシン上のファイルの保存先です。 あなたのマシンに +`"data"`というフォルダを用意し、そこにファイルをダウンロードする必要があります。 そこで、このコマンドは +リモートファイルをダウンロードし、`"rnaseq.csv"` という名前を付けて、`"data"\` という名前の +フォルダに追加する。 + +```{r, eval=TRUE} +download.file(url = "https://github.com/carpentries-incubator/bioc-intro/raw/main/episodes/data/rnaseq.csv", + destfile = "data/rnaseq.csv") +``` + +これでデータをロードする準備ができた: + +```{r, eval=TRUE, purl=TRUE} +rna <- read.csv("data/rnaseq.csv") +``` + +、代入は何も表示しないからだ。 +、データがロードされたことを確認したい場合は、 +、その名前をタイプすることでデータフレームの中身を見ることができる: + +```{r, eval=FALSE} +RNA +``` + +うわぁ...。 多くのアウトプットがあった。 少なくとも、 +。 関数 `head()` を使って、このデータ・フレーム +の先頭(最初の6行)をチェックしてみよう: + +```{r, purl=TRUE} +head(rna) +## +## View(rna)も試してみる。 +``` + +**注**\*。 + +read.csv()`は、フィールドがカンマで区切られていると仮定しているが、 +いくつかの国では、カンマは小数の区切り文字として使用され、 +セミコロン(;)はフィールドの区切り文字として使用される。 Rでこの種のファイルを +、 `read.csv2()`関数を使うことができる。 +`read.csv()`と全く同じ動作をするが、 +小数とフィールドのセパレーターに異なるパラメーターを使用する。 別の +フォーマットを使用している場合は、ユーザーが両方指定することができます。 詳しくは、 +`read.csv()`のヘルプを`?read.csv`と入力して確認してください。 また、`read.delim()`関数があり、タブ区切りのデータファイルを読み込むことができる。 +重要なことは、これらの関数はすべて、 +メインの`read.table()` 関数に異なる引数を指定するためのラッパー関数であるということです。 そのため、 +上のデータは、`read.table()`、区切りの引数を`,\` にしてロードすることもできた。 コードは以下の通り: + +```{r, eval=TRUE, purl=TRUE} +rna <- read.table(file = "data/rnaseq.csv", + sep = ",", + header = TRUE) +``` + +デフォルトでは `read.table()` の header 引数は +FALSE に設定されているので、 +のヘッダーを読むためには header 引数を TRUE に設定しなければならない。 + +## データフレームとは? + +データ・フレームは、ほとんどの表データ、 +、統計やプロットに使われる_事実上の_データ構造である。 + +データフレームは手作業で作成することもできますが、最も一般的なのは、関数 `read.csv()` や `read.table()` によって生成される +データフレームです。 + +データフレームとは、 +、列がすべて同じ長さのベクトルである表の形式でデータを表現したものである。 +、列はベクトルであるため、各列は1種類のデータ +(文字、整数、因子など)を含まなければならない。 例えば、 +、数値、文字、 +論理ベクトルからなるデータフレームを示す図である。 + +![](./fig/data-frame.svg) + +str()\`という関数で +: + +```{r} +str(rna) +``` + +## data.frame\` オブジェクトの検査 + +関数 `head()` と `str()` が、 +データフレームの内容と構造をチェックするのに便利であることは、すでに説明した。 以下は、 +データの内容/構造を知るための、 +非網羅的な機能のリストである。 試してみよう! + +\*\*サイズ + +- dim(rna)\` - 行数を最初の + 要素とし、列数を2番目の要素(オブジェクトの + **dim**ensions )とするベクトルを返す。 +- nrow(rna)\` - 行の数を返す。 +- ncol(rna)\` - 列数を返す。 + +\*\*内容 + +- head(rna)\` - 最初の6行を表示する。 +- tail(rna)\` - 最後の6行を表示する。 + +**名前**: + +- names(rna)`- 列名を返す(`data.frame`オブジェクトの`colnames()\` と同義)。 +- rownames(rna)\` - 行の名前を返す。 + +**要約**: + +- str(rna)\` - オブジェクトの構造と、 + クラス、各カラムの長さと内容に関する情報。 +- `summary(rna)` - 各カラムの要約統計量。 + +注:これらの関数のほとんどは "ジェネリック "であり、`data.frame`以外の +オブジェクトにも使用できます。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジだ: + +str(rna)\`の出力に基づいて、以下の +の質問に答えられるか? + +- オブジェクト `rna` のクラスは何ですか? +- このオブジェクトにはいくつの行といくつの列がありますか? + +::::::::::::::: solution + +## ソリューション + +- クラス: データ・フレーム +- 行数:66465、列数:11:11 + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## データフレームのインデックス化とサブセット化 + +rna\`データフレームには行と列がある(2次元ある)。 +、そこから特定のデータを抽出したい場合は、 +「座標」を指定する必要がある。 行番号が最初に来て、 +列番号がそれに続く。 しかし、これらの +座標を指定する方法が異なれば、異なるクラスの結果が得られることに注意されたい。 + +```{r, eval=FALSE, purl=TRUE} +# データフレームの1列目の最初の要素(ベクトルとして) +rna[1, 1] +# 6列目の最初の要素(ベクトルとして) +rna[1, 6] +# データフレームの1列目の要素(ベクトルとして) +rna[, 1] +# データフレームの1列目の要素(data.フレームとして) +rna[1] +# 7列目の最初の3要素(ベクトルとして) +rna[1:3, 7] +# データフレームの3行目(data.frameとして) +rna[3, ] +# head_rna <- head(rna) +head_rna <- rna[1:6, ] +head_rna +``` + +1:10`と `10:1\`は +の例で、 +の増加または減少の順序で整数の数値ベクトルを作成する特別な関数である。 詳しくは@ref(sec:genvec)を参照のこと。 + +また、「`-`」記号を使ってデータフレームの特定のインデックスを除外することもできる: + +```{r, eval=FALSE, purl=TRUE} +rna[, -1] ## 最初の列を除いたデータフレーム全体 +rna[-c(7:66465), ] ## head(rna)と等価 +``` + +データフレームは、インデックス(前に示したように)や +、列名を直接呼び出してサブセットすることもできる: + +```{r, eval=FALSE, purl=TRUE} +rna["gene"] # Result is a data.frame +rna[, "gene"] # Result is a vector +rna[["gene"]]. # 結果はベクトル +rna$gene # 結果はベクトル +``` + +RStudio では、オートコンプリート機能を使用して、列の完全で +正しい名前を取得できます。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ + +1. データセット `rna` の + 行 200 番目のデータのみを含む `data.frame` (`rna_200`) を作成する。 + +2. nrow()`が`data.frame\`の行数を示していることに気づいただろうか? + +- この数字を使って、最初の + `rna`データフレームの最後の行だけを取り出す。 + +- tail()\`を使った最後の行と比較し、 + 、期待に応えていることを確認する。 + +- 行番号の代わりに `nrow()` を使って最後の行を取り出す。 + +- 最後の行から新しいデータフレーム(`rna_last`)を作成する。 + +3. `rna` データフレームの中央にある行を抽出するには `nrow()` を使用する。 この行の内容をオブジェクト + `rna_middle` に格納する。 + +4. nrow()`と上記の `-` 表記を組み合わせると、rnaデータセットの1行目から6行目までの + 行だけを保持し、`head(rna)\`の + 挙動を再現することができる。 + +::::::::::::::: solution + +## ソリューション + +```{r, purl=TRUE} +## 1. +rna_200 <- rna[200, ] +## 2. +## Saving `n_rows` to improve readability and reduce duplication +n_rows <- nrow(rna) +rna_last <- rna[n_rows, ] +## 3. +rna_middle <- rna[n_rows / 2, ] +## 4. +rna_head <- rna[-(7:n_rows), ] +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## 要因 + +要因は**カテゴリーデータ**を表す。 これらは、 +ラベルに関連付けられた整数として格納され、順序付けされたものであっても、順序付けされていないものであってもよい。 +因子は文字ベクトルのように見える(そしてしばしば振舞う)が、 +、実際にはRでは整数ベクトルとして扱われる。そのため、文字列として扱う場合は非常に +注意する必要がある。 + +いったん作成されたファクターは、あらかじめ定義された値のセット( +、_レベル_として知られている)しか含むことができない。 デフォルトでは、Rは常にレベルをアルファベット順( +)でソートする。 例えば、2つのレベルを持つ因子があるとする: + +```{r, purl=TRUE} +セックス <- factor(c("male", "female", "female", "male", "female")) +``` + +Rは`1`をレベル`"female"`に、`2`をレベル +`"male"`に割り当てる(このベクトルの最初の要素 +が`"male"`であるにもかかわらず、`f`が`m`の前に来るため)。 これは、 +`levels()` という関数を使うことで見ることができ、`nlevels()` を使えばレベル数を知ることができる: + +```{r, purl=TRUE} +levels(sex) +nlevels(sex) +``` + +要因の順番が重要でない場合もあるが、 +、意味がある(例えば、"low"、 +"medium"、"high")、視覚化が向上する、または特定のタイプの分析で必要である( +)ため、順番を指定したい場合もある。 ここで、 +`sex`ベクトルでレベルを並べ替える一つの方法は次のようになる: + +```{r, purl=TRUE} +sex ## current order +sex <- factor(sex, levels = c("male", "female")) +sex ## after re-ordering +``` + +Rの記憶では、これらの因子は整数(1, 2, 3)、 +で表現されるが、因子は自己 +を記述するため、整数よりも情報量が多い。`"女性"`、`"男性"`は`1`、 +`2`よりも説明的である。 どちらが "男性 "ですか?\ +の整数データだけではわからないだろう。 一方、ファクターはこの情報を内蔵している。 +特に、レベルが多い場合(例のデータセットの +遺伝子バイオタイプのような)に便利である。 + +データが因子として格納されているとき、各因子レベルによって表現されるオブザベーションの数 +を素早く見るために、 `plot()` +関数を使うことができます。 データ中の男性 +、女性の数を見てみよう。 + +```{r firstfactorplot, fig.cap="Bar plot of the number of females and males.", purl=TRUE} +プロット(性) +``` + +### 文字への変換 + +因数を文字ベクトルに変換する必要がある場合は、 +`as.character(x)`. + +```{r, purl=TRUE} +as.character(性) +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +### 要因の名称変更 + +これらのファクターの名前を変えたい場合は、 +: + +```{r, purl=TRUE} +levels(sex) +levels(sex) <- c("M", "F") +sex +plot(sex) +``` + +:::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジだ: + +- F "と "M "の名前をそれぞれ "Female "と "Male "に変更する。 + +::::::::::::::: solution + +## ソリューション + +```{r, eval=TRUE, purl=TRUE} +levels(sex) +levels(sex) <- c("Male", "Female") +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジだ: + +read.csv()`を使ってデータフレームを作成する方法を見てきましたが、 +`data.frame()`関数を使って手作業で作成することもできます。 +この手作りの`data.frame\`にはいくつか間違いがある。 +、それを見つけて修正することはできますか? 実験することをためらってはいけない! + +```{r, eval=FALSE} +animal_data <- data.frame( + animal = c(dog, cat, sea cucumber, sea nurchin), + feel = c("furry", "squishy", "spiny"), + weight = c(45, 8 1.1, 0.8)) +``` + +::::::::::::::: solution + +## ソリューション + +- 動物の名前の周りに引用符がない +- "feel "欄に1つ記入がない(おそらく毛皮の動物の1つ)。 +- 体重欄のコンマが1つ足りない + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジだ: + +次の +の例で、各列のクラスを予測できますか? + +str(country_climate)\`を使って推測をチェックする: + +- 期待通りですか? なぜですか? なぜだ? + +- データフレームを作成する際に、最後の + 変数の後に `stringsAsFactors = TRUE` を追加してもう一度試してみてください。 今、何が起きているのか? + stringsAsFactors`は、`read.csv()\`を使ってテキストベースの + のスプレッドシートをRに読み込むときにも設定できる。 + +```{r, eval=FALSE, purl=TRUE} +country_climate <- data.frame( + country = c("Canada", "Panama", "South Africa", "Australia"), + climate = c("cold", "hot", "temperate", "hot/temperate")、 + temperature = c(10, 30, 18, "15"), + northern_hemisphere = c(TRUE, TRUE, FALSE, "FALSE"), + has_kangaroo = c(FALSE, FALSE, FALSE, 1) +) +``` + +::::::::::::::: solution + +## ソリューション + +```{r, eval=TRUE, purl=TRUE} +country_climate <- data.frame( + country = c("Canada", "Panama", "South Africa", "Australia"), + climate = c("cold", "hot", "temperate", "hot/temperate"), + temperature = c(10, 30, 18, "15"), + northern_hemisphere = c(TRUE, TRUE, FALSE, "FALSE"), + has_kangaroo = c(FALSE, FALSE, FALSE, 1) + ) +str(country_climate) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +データ型の自動変換は、時に恵みであり、時に +迷惑である。 その存在を認識し、ルールを学び、Rでインポートするデータ +がデータフレーム内で正しい型であることを再確認すること。 そうでない場合は、 +データ入力中に生じたかもしれないミス(例えば、数字しか入っていないはずの列に文字が入っている)を検出するために、 +を活用する。 + +詳しくはRStudio +チュートリアルをご覧ください。 + +## マトリックス + +先に進む前に、データ・フレームについて学んだので、 +パッケージのインストールを復習し、新しいデータ型、すなわち +`matrix` について学んでみよう。 data.frame`のように、行列は行と +列の2つの次元を持つ。 しかし大きな違いは、`行列`のすべてのセルは +同じ型でなければならないということである:numeric`、`character`、`logical`、... +その点で、行列は `data.frame` よりも `vector` に近い。 + +行列のデフォルトコンストラクタは `matrix` である。 行列を構成するための +の値のベクトルと、行および/または +の列数[^ncol]を取る。 下の図( +)のように、値は列に沿ってソートされる。 + +```{r mat1, purl=TRUE} +m <- matrix(1:9, ncol = 3, nrow = 3) +m +``` + +[^ncol]: 行数か列数のどちらかだけで十分で、もう一方は値の長さから推測できる。 値と行/列の数が合わない場合に何が起こるか試してみてください。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジだ: + +installed.packages()`という関数を使って、 +あなたのコンピューターに現在インストールされているすべてのパッケージの情報を含む `文字\`行列 +を作成します。 探検してみよう。 + +::::::::::::::: solution + +## 解決策 + +```{r pkg_sln, eval=FALSE, purl=TRUE} +## +ip <- installed.packages() +head(ip) +## View(ip) +## パッケージの数 +nrow(ip) +## インストールされている全てのパッケージの名前 +rownames(ip) +## 各パッケージに関する情報の種類 +colnames(ip) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +テストデータとして、大規模なランダムデータ行列を作成することはしばしば有用である。 以下の練習問題は、平均0、標準偏差 +1の正規分布から無作為に +データを抽出して、そのような行列を作成するものです。これは `rnorm()` 関数で行うことができます。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジだ: + +正規分布データ +(平均0、標準偏差1)の次元1000×3の行列を作る。 + +::::::::::::::: solution + +## ソリューション + +```{r rnormmat_sln, purl=TRUE} +set.seed(123) +m <- matrix(rnorm(3000), ncol = 3) +dim(m) +head(m) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## 日付の書式設定 + +新人(そしてベテラン!)が抱える最も一般的な問題の1つである。 Rユーザーは、 +、日付と時刻の情報を、 +適切で分析中に使用可能な変数に変換している。 + +### 表計算ソフトの日付に関する注意 + +スプレッドシートの日付は通常、1つの列に格納される。 +これが日付を記録する最も自然な方法のように思えるが、実際には +ベストプラクティスではない。 スプレッドシート・アプリケーションは、 +一見正しい方法で日付を表示する(人間の観察者には)。しかし、実際に +どのように日付を処理し、保存するかには問題があるかもしれない。 YEAR、MONTH、DAYを別々のカラムに、または +、YEARとDAY-OF-YEARを別々のカラムに保存した方が、 +より安全な場合が多い。 + +LibreOffice、Microsoft Excel、OpenOffice、 +Gnumericなどの表計算プログラム。 は、 +日付のエンコード方法が異なる(そしてしばしば互換性がない)(同じプログラムであっても、バージョンやオペレーティング +システム間で)。 さらに、エクセルは日付でないものを +日付に変える +(@Zeeberg:2004)ことができる。例えば、MAR1、DEC1、 +OCT4のような名前や識別子である。 そのため、全体的に日付フォーマットを避けているのであれば、 +、こうした問題を特定しやすくなる。 + +Data CarpentryレッスンのDates as +data +セクションでは、スプレッドシートを使った日付の落とし穴について、さらなる洞察 +を提供しています。 + +**lubridate`** パッケージの `ymd()` 関数を使用します (**tidyverse`** に属します。詳しくは +[こちら](https://www.tidyverse.org/))。 . \*\*lubridate`**は**tidyverse`\*\*のインストールの一部として +。 +**`tidyverse`** (`library(tidyverse)`) をロードすると、コアパッケージ (ほとんどのデータ分析で使用される +パッケージ) がロードされます。 **`lubridate`** +しかし、コアTidyverseには属さないので、 +`library(lubridate)`で明示的にロードする必要があります。 + +必要なパッケージをロードすることから始める: + +```{r loadlibridate, message=FALSE, purl=TRUE} +library("lubridate") +``` + +ymd()`は年、月、日を表すベクトルを受け取り、 +`Date`ベクトルに変換する。 Date`はRが +、日付であると認識するデータのクラスであり、そのように操作することができる。 +関数が必要とする引数は柔軟であるが、ベストプラクティスとしては、"YYYY-MM-DD "としてフォーマットされた文字 +ベクトルである。 + +日付オブジェクトを作成し、構造を調べてみよう: + +```{r, purl=TRUE} +my_date <- ymd("2015-01-01") +str(my_date) +``` + +では、年、月、日を別々に貼り付けてみよう: + +```{r, purl=TRUE} +# sep は各コンポーネントを区切るために使う文字を示す +my_date <- ymd(paste("2015", "1", "1", sep = "-")) +str(my_date) +``` + +それでは、典型的な日付操作 +のパイプラインに慣れておこう。 以下の小さなデータには、異なる `year`、 +`month`、`day` 列に日付が格納されている。 + +```{r, purl=TRUE} +x <- data.frame(year = c(1996, 1992, 1987, 1986, 2000, 1990, 2002, 1994, 1997, 1985), + month = c(2, 3, 10, 1, 8, 3, 4, 5, 5), + day = c(24, 8, 1, 5, 8, 17, 13, 10, 11, 24), + value = c(4, 5, 1, 9, 3, 8, 10, 2, 6, 7)) +x +``` + +次に、この関数を `x` データセットに適用する。 まず、`paste()` を使って、`x` +の `year`、`month`、`day` 列から +の文字ベクトルを作る: + +```{r, purl=TRUE} +paste(x$year, x$month, x$day, sep = "-") +``` + +この文字ベクトルは `ymd()` の引数として使うことができる: + +```{r, purl=TRUE} +ymd(paste(x$year, x$month, x$day, sep = "-")) +``` + +出来上がった `Date` ベクトルは `x` に `date` という新しいカラムとして追加することができる: + +```{r, purl=TRUE} +x$date <- ymd(paste(x$year, x$month, x$day, sep = "-")) +str(x) # '日付'をクラスとする新しいカラムに注目。 +``` + +すべてが正しく機能していることを確認しよう。 +新しいカラムを検査する一つの方法は、`summary()`を使うことである: + +```{r, purl=TRUE} +summary(x$date) +``` + +ymd()`は、年、月、日を +の順番で持つことを期待している。 例えば、日、月、年があれば、 +`dmy()\` が必要になる。 + +```{r, purl=TRUE} +dmy(paste(x$day, x$month, x$year, sep = "-")) +``` + +lubdridate\`は、あらゆる日付のバリエーションに対応する多くの関数を持っている。 + +## Rオブジェクトの概要 + +これまで、次元数( +)、格納できるデータの種類( +)が単一か複数かによって異なる、いくつかのタイプのRオブジェクトを見てきた: + +- **vector\`**:1次元(長さがある)、1種類のデータ。 +- **マトリックス\`**:2次元、単一データ型。 +- **data.frame\`**:2次元、1列1型。 + +## リスト + +まだ見ていないが、知っておくと便利なデータ型がリストだ。 +、先ほどのまとめから続く: + +- **`list`**: 1つの次元で、各項目は異なるデータ + 型にすることができる。 + +以下では、数値、文字、 +行列、データフレーム、別のリストのベクトルを含むリストを作ってみよう: + +```{r list0, purl=TRUE} +l <- list(1:10, ## numeric + letters, ## character + installed.packages(), ## a matrix + cars, ## a data.frame + list(1, 2, 3)) ## a list +length(l) +str(l) +``` + +リストのサブセットは `[]` を使って新しいサブリストをサブセットするか、`[]]` +を使ってそのリストの単一要素を取り出す( +リストに名前がついている場合は、インデックスか名前を使う)。 + +```{r, purl=TRUE} +l[[1]]## +l[1:2] ## 長さ 2 のリスト +l[1] ## 長さ 1 のリスト +``` + +## 表形式データのエクスポートと保存 {#sec:exportandsave} + +`read.table` ファミリーの関数を使って、テキストベースのスプレッドシートをRに読み込む方法を見てきた。 data.frame`を +テキストベースのスプレッドシートにエクスポートするには、 +関数の `write.table` セット(`write.csv`, `write.delim`, ...)を使用します。 これらはすべて、 +エクスポートする変数と、エクスポートするファイルを指定する。 例えば、 +`rna`のデータを`data_output`ディレクトリの`my_rna.csv\` ファイルにエクスポートするには、次のように実行する: + +```{r, eval=FALSE, purl=TRUE} +write.csv(rna, file = "data_output/my_rna.csv") +``` + +この新しいcsvファイルは、 +、Rに精通していない他の共同研究者と共有することができます。`data.frame`のフィールドの一部(例えば、"product "列を参照)にカンマがあるにもかかわらず、Rはデフォルトで +、各フィールドを引用符で囲みます。したがって、 +、列の区切り文字としてカンマを使用しているにもかかわらず、 +、Rに正しく読み込むことができます。 + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Rでの表形式データ + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/ja/episodes/30-dplyr.Rmd b/locale/ja/episodes/30-dplyr.Rmd new file mode 100644 index 000000000..76aadb9e7 --- /dev/null +++ b/locale/ja/episodes/30-dplyr.Rmd @@ -0,0 +1,1101 @@ +--- +source: Rmd +title: dplyrによるデータの操作と分析 +teaching: 75 +exercises: 75 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- dplyr`** と **tidyr`\*\* パッケージの目的を説明する。 +- データを操作するのに非常に便利な関数をいくつか説明する。 +- ワイド表形式とロング表形式の概念を説明し、 + 、データ・フレームを一方の形式から他方の形式に変更する方法を見る。 +- テーブルの結合方法を示す。 + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- tidyverseメタパッケージを用いたRでのデータ分析 + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +```{r loaddata_dplyr2, echo=FALSE, purl=FALSE, message=FALSE} +if (!file.exists("data/rnaseq.csv")) +download.file(url = "https://github.com/carpentries-incubator/bioc-intro/raw/main/episodes/data/rnaseq.csv", + destfile = "data/rnaseq.csv") +``` + +> このエピソードは、Data Carpentriesの_Data Analysis and +> Visualisation in R for Ecologists_レッスンに基づいています。 + +## dplyr`**と**tidyr`\*\*を使ったデータ操作 + +ブラケット・サブセットは便利だが、煩雑で +、特に複雑な操作では読みにくい。 + +いくつかのパッケージは、データを操作する際に私たちの作業を大いに助けてくれる。 +Rのパッケージは基本的に、 +、より多くのことができるようにする追加関数のセットである。 いくつかのパッケージは、データを操作する際に私たちの作業を大いに助けてくれる。 +Rのパッケージは基本的に、 +、より多くのことができるようにする追加関数のセットである。 これまで使ってきた `str()` や +`data.frame()` などの関数は、Rに組み込まれています。パッケージをロードすることで、その他の +固有の関数にアクセスできるようになります。 初めてパッケージを使用する前に、 +をマシンにインストールする必要がある。その後、 +R セッションでパッケージが必要になったら、毎回インポートする必要がある。 初めてパッケージを使用する前に、 +をマシンにインストールする必要がある。その後、 +R セッションでパッケージが必要になったら、毎回インポートする必要がある。 + +- dplyr\\`\*\* パッケージは、データ操作タスクのための強力なツールを提供します。 + データフレームを直接操作できるように構築されており、多くの操作タスクが + に最適化されている。 + データフレームを直接操作できるように構築されており、多くの操作タスクが + に最適化されている。 + +- 後述するように、 + 、特定の分析や視覚化を行うために、データフレームの形を変えたいことがある。 tidyr\`\*\*パッケージは、 + 、データの形を変えるというこの一般的な問題に対処し、 + データを整然と操作するためのツールを提供する。 + +ワークショップの後、\*\*dplyr`**と**tidyr`\*\*についてもっと知りたい方は、 +、こちらのhandy data transformation with +をご覧ください。 + +- tidyverse`**パッケージは "umbrella-package "であり、 + 、データ解析のためのいくつかの便利なパッケージがインストールされます。 + には、**tidyr`\*\*, **dplyr`**, **ggplot2`**, \*\*tibble\\`\*\*などがあります。 + これらのパッケージは、データを操作したり対話したりするのに役立ちます。 + サブセット化、変換、 + ビジュアライズなど、データを使ってさまざまなことができる。 + サブセット化、変換、 + ビジュアライズなど、データを使ってさまざまなことができる。 + +セットアップを行ったのであれば、すでにtidyverseパッケージがインストールされているはずです。 +ライブラリから読み込んでみて、それがあるかどうか確認してください: +ライブラリから読み込んでみて、それがあるかどうか確認してください: + +```{r, message=FALSE, purl=TRUE} +## dplyr を含む tidyverse パッケージをロード +library("tidyverse") +``` + +tidyverse\\`\*\* パッケージをインストールするには、以下のようにタイプしてください: + +```{r, eval=FALSE, purl=TRUE} +BiocManager::install("tidyverse") +``` + +もし、\*\*tidyverse`**パッケージをインストールしなければならなかったなら、上記の`library()\\`コマンドを使って、このRセッションでロードすることを忘れないでください! + +## tidyverseでデータをロードする + +read.csv()`の代わりに、tidyverseパッケージ **readr`\*\*の `read_csv()` +関数(`.`の代わりに`_`があることに注意)を使ってデータを読み込みます。 + +```{r, message=FALSE, purl=TRUE} +rna <- read_csv("data/rnaseq.csv") + +## データを見る +rna +``` + +データのクラスが "tibble "と呼ばれていることに注目してほしい。 + +Tibblesは、以前 +で紹介したデータ・フレーム・オブジェクトの動作の一部を微調整している。 データ構造はデータフレームによく似ている。 +我々の目的にとって、唯一の違いはそれだ: + +1. 各列のデータ型が列名の下に表示される。 + <`dbl`\> は + の小数点を持つ数値を保持するために定義されたデータ型である。 + データで作業するとき、我々はしばしば、各因子または因子の組み合わせについて + 見つかったオブザベーションの数を知りたい。 このタスクのために、\*\*dplyr`** は + `count()\\` を提供している。 例えば、感染したサンプルと感染していないサンプルそれぞれについて、 + 、データの行数をカウントしたい場合、次のようにする: + +2. これは、データの最初の数行と、 + 1画面に収まるだけの列数だけを印刷する。 + +これから、最も一般的な **dplyr\\`** 関数のいくつかを学びます: + +- select()\\`: カラムのサブセット +- `filter()`: 条件で行をサブセットする。 +- mutate()\\`: 他のカラムの情報を使って新しいカラムを作成する。 +- group_by()`と`summarise()\\`: グループ化されたデータの要約統計量を作成する。 +- arrange()\\`:結果の並べ替え +- count()\\`: 離散値を数える + +## 列の選択と行のフィルタリング + +データフレームの列を選択するには `select()` を使う。 この関数の最初の引数 +はデータフレーム (`rna`) で、続く +の引数は保持する列です。 Tibblesは、以前 +で紹介したデータ・フレーム・オブジェクトの動作の一部を微調整している。 データ構造はデータフレームによく似ている。 +我々の目的にとって、唯一の違いはそれだ: + +```{r, purl=TRUE} +select(rna, gene, sample, tissue, expression) +``` + +特定の列を除く\*すべての列を選択するには、 +その変数の前に"-"を付けて除外する。 + +```{r, purl=TRUE} +select(rna, -tissue, -organism) +``` + +これは `rna` の中の、 +`tissue` と `organism` 以外のすべての変数を選択する。 + +特定の条件に基づいて行を選択するには、`filter()` を使用する: + +```{r, purl=TRUE} +filter(rna, sex == "Male") +filter(rna, sex == "Male" & infection == "NonInfected") +``` + +ここで、このデータセットで解析されたマウス +遺伝子のヒトホモログに興味があるとしよう。 この情報は、 +`hsapiens_homolog_associated_gene_name` という名前の `rna` tibbleの +最後のカラムにある。 ここで、このデータセットで解析されたマウス +遺伝子のヒトホモログに興味があるとしよう。 この情報は、 +`hsapiens_homolog_associated_gene_name` という名前の `rna` tibbleの +最後のカラムにある。 簡単に視覚化するために、 +、2つの列`gene`と +`hsapiens_homolog_associated_gene_name`だけを含む新しいテーブルを作成する。 + +```{r} +genes <- select(rna, gene, hsapiens_homolog_associated_gene_name) +genes +``` + +マウス遺伝子の中にはヒトにホモログがないものもある。 これらは、 +`filter()` と、 +何かが `NA` かどうかを判定する `is.na()` 関数を使って取得することができる。 + +```{r, purl=TRUE} +filter(genes, is.na(hsapiens_homolog_associated_gene_name)) +``` + +ヒトのホモログを持つマウス遺伝子だけを保持したい場合、 +、結果を否定する"!"記号を挿入することができる。したがって、 +、hsapiens_homolog_associated_gene_name _is not_ an +`NA` となるすべての行を求めることになる。 + +```{r, purl=TRUE} +filter(genes, !is.na(hsapiens_homolog_associated_gene_name)) +``` + +## パイプ + +選択とフィルタを同時に行いたい場合は? これを行うには、 +、中間ステップ、ネストされた関数、パイプの3つの方法がある。 これを行うには、 +、中間ステップ、ネストされた関数、パイプの3つの方法がある。 + +中間ステップでは、一時的なデータフレームを作成し、 +、次の関数の入力として使用する: + +```{r, purl=TRUE} +rna2 <- filter(rna, sex == "Male") +rna3 <- select(rna2, gene, sample, tissue, expression) +rna3 +``` + +これは読みやすいが、 +、個別に名前を付けなければならない中間オブジェクトがたくさんあるため、ワークスペースが散らかる可能性がある。 複数の +、それを把握するのは難しいかもしれない。 複数の +、それを把握するのは難しいかもしれない。 + +、関数を入れ子にすることもできる: + +```{r, purl=TRUE} +rna3 <- select(filter(rna, sex == "Male", gene, sample, tissue, expression)) +rna3 +``` + +これは便利だが、 +Rは式を内側から外側へと評価する(この場合、フィルタリングしてから選択する)ため、関数が入れ子になりすぎると読みにくくなることがある。 + +最後のオプションである_パイプ_は、Rに最近追加されたものである。パイプを使うと、ある関数の出力を +、次の関数に直接送ることができる。これは、同じデータセットに対して多くの処理を行う必要がある場合に便利である +。 + +ミューテート R のパイプは `%>%` (**`magrittr`** +パッケージで利用可能) または `|>` (ベース R で利用可能) のように見えます。 RStudioを使用する場合は、 +PCをお持ちの場合はCtrl+Shift+M、 +Macをお持ちの場合はCmd+Shift+Mでパイプを +。 + +上記のコードでは、パイプを使って `rna` データセットをまず +`filter()` を通して `sex` が Male である行を残し、次に +`select()` を通して `gene`, `sample`, `tissue`, +`expression`columns だけを残すように送っている。 + +パイプ `%>%` はその左側にあるオブジェクトを受け取り、 +その右側にある関数の最初の引数として直接渡します。 +`filter()` と +`select()` 関数の引数として明示的にデータフレームを含める必要はもうありません。 + +```{r, purl=TRUE} +rna %>% + filter(sex == "Male") %>% + select(gene, sample, tissue, expression) +``` + +パイプを "then "のように読むことが役に立つと思う人もいるだろう。 パイプを "then "のように読むことが役に立つと思う人もいるだろう。 例えば、 +上の例では、データフレーム `rna` を取得し、`sex=="Male"` の行を +で `フィルター`し、`gene`, `sample`, +`tissue`, `expression` の列を `選択` した。 + +dplyr\\`\*\*関数はそれ自体ではやや単純だが、 +、パイプを使った線形ワークフローに組み合わせることで、 +、データフレームのより複雑な操作を行うことができる。 + +この小さいバージョンのデータで新しいオブジェクトを作りたい場合、 +、新しい名前を割り当てることができる: + +```{r, purl=TRUE} +rna3<- rna %>% + filter(sex == "Male") %>% + select(gene, sample, tissue, expression) + +rna3 +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジだ: + +パイプを使用して、時間0、 +、遺伝子の発現が50000より高い雌マウスのオブザベーションを保持するように`rna`データをサブセットし、 +`gene`、`sample`、`time`、`expression`、`age`の列のみを保持する。 + +::::::::::::::: solution + +## ソリューション + +```{r} +rna %>% + filter(expression > 50000, + sex == "Female", + time == 0 ) %>% + select(gene, sample, time, expression, age) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## ミューテート + +例えば、単位変換をしたり、2つの +列の値の比率を求めたりするために、既存の +列の値に基づいて新しい列を作成したいことがよくあります。 これには `mutate()` を使う。 これには `mutate()` を使う。 + +時間単位の新しい列を作成する: + +```{r, purl=TRUE} +rna %>% + mutate(time_hours = time * 24) %>% + select(time, time_hours) +``` + +また、`mutate()`の同じ呼び出しの中で、最初の新しいカラムに基づいて2番目の新しいカラムを作成することもできる: + +```{r, purl=TRUE} +rna %>% + mutate(time_hours = time * 24, + time_mn = time_hours * 60) %>% + select(time, time_hours, time_mn) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ + +後述するように、 +、特定の分析や視覚化を行うために、データフレームの形を変えたいことがある。 tidyr\`\*\*パッケージは、 + 、データの形を変えるというこの一般的な問題に対処し、 + データを整然と操作するためのツールを提供する。 +の値は対数変換する。 以下の +条件を満たす `rna`データから新しいデータフレームを作成する:`gene`、`chromosome_name`、 +`phenotype_description`、`sample`、`expression\` 列のみを含む。 +の値は対数変換する。 このデータフレームは、 +、性染色体に位置し、 +phenotype_descriptionに関連し、log expressionが5より高い遺伝子のみを含んでいなければならない。 + +**ヒント**:このデータフレームを +、どのようにコマンドを並べるべきか考えてみよう! + +::::::::::::::: solution + +## ソリューション + +```{r, eval=TRUE, purl=TRUE} +rna %>% + mutate(expression = log(expression)) %>% + select(gene, chromosome_name, phenotype_description, sample, expression) %>% + filter(chromosome_name == "X" | chromosome_name == "Y") %>% + filter(!is.na(phenotype_description)) %>% + filter(expression > 5) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## 分割-適用-結合データ分析 + +多くのデータ分析タスクは、 +_split-apply-combine_パラダイムを使ってアプローチすることができる:データをグループに分割し、各グループにいくつかの +分析を適用し、その結果を組み合わせる。 \*\*dplyr`** +は `group_by()\` 関数を使って、これを非常に簡単にしている。 **dplyr`\*\* +は `group_by()` 関数を使って、これを非常に簡単にしている。 + +```{r} +rna %>% + group_by(gene) +``` + +group_by()`関数はデータ処理を行わず、 +データをサブセットにグループ化する。上の例では、 +`r nrow(rna)`オブザベーションの最初の`tibble`は、`r length(unique(rna$gene))`グループに`gene\\` 変数に基づいて分割される。 + +同様に、ティブルをサンプルごとにグループ分けすることもできる: + +```{r} +rna %>% + group_by(sample) +``` + +ここで、最初の `r nrow(rna)` オブザベーションの `tibble` は、`sample` 変数に基づいて、 +`r length(unique(rna$sample))` グループに分割される。 + +いったんデータがグループ化されると、その後の操作は各グループに独立して +。 + +### summarise()\`関数 + +group_by()`は`summarise()\\` と一緒に使われることが多く、 +は各グループを1行の要約に折りたたむ。 + +group_by()` は、 **カテゴリー** 変数を含むカラム名を引数として取り、 +統計のサマリーを計算します。 group_by()\` は、 +**カテゴリー** 変数を含むカラム名を引数として取り、 +統計のサマリーを計算します。 そこで、遺伝子ごとの平均「発現」を計算する: + +```{r} +rna %>% + group_by(gene %>% + summarise(mean_expression = mean(expression)) +``` + +また、各サンプルの全遺伝子の平均発現量を計算することもできる: + +```{r} +rna %>% + group_by(sample %>% + summarise(mean_expression = mean(expression)) +``` + +しかし、複数の列でグループ化することもできる: + +```{r} +rna %>% + group_by(gene, infection, time) %>% + summarise(mean_expression = mean(expression)) +``` + +いったんデータがグループ化されると、同じ +(必ずしも同じ変数でなくてもよい)時間に複数の変数を要約することもできる。 例えば、遺伝子別、条件別の「発現」の中央値を示す +列を追加することができる: 例えば、遺伝子別、条件別の「発現」の中央値を示す +列を追加することができる: + +```{r, purl=TRUE} +rna %>% + group_by(gene, infection, time) %>% + summarise(mean_expression = mean(expression), + median_expression = median(expression)) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ + +遺伝子 "Dok3 "のタイムポイントごとの平均発現量を計算する。 + +::::::::::::::: solution + +## ソリューション + +```{r, purl=TRUE} +rna %>% + filter(gene == "Dok3") %>% + group_by(time) %>% + summarise(mean = mean(expression)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +### カウント + +データで作業するとき、我々はしばしば、各因子または因子の組み合わせについて +見つかったオブザベーションの数を知りたい。 このタスクのために、\*\*dplyr`** は +`count()\` を提供している。 例えば、感染したサンプルと感染していないサンプルそれぞれについて、 +、データの行数をカウントしたい場合、次のようにする: + +```{r, purl=TRUE} +rna %>% + count(infection) +``` + +count()`関数は、すでに見たことのある、変数でグループ化し、そのグループ内のオブザベーションの数をカウントして要約する、ということの省略記法です。 言い換えれば、`rna %>% count(infection)\`は次のものと等価である: 言い換えれば、`rna %>% count(infection)\`は次のものと等価である: + +```{r, purl=TRUE} +rna %>% + group_by(infection) %>% + summarise(n = n()) +``` + +先ほどの例では、`count()` を使って、_1つの_要因(つまり`感染`)について +、行数/観察数を数えている。 +先ほどの例では、`count()` を使って、_1つの_要因(つまり`感染`)について +、行数/観察数を数えている。 +もし、`感染`と`時間`のような_要因の組み合わせ_をカウントしたいのであれば、 +、`count()`の引数として1つ目と2つ目の要因を指定することになる: + +```{r, purl=TRUE} +rna %>% + count(infection, time) +``` + +これと等価である: + +```{r, purl=TRUE} +rna %>% + group_by(infection, time) %>% + summarise(n = n()) +``` + +比較を容易にするために、結果を並べ替えると便利なことがある。 +arrange()\`を使って表を並べ替えることができる。 +例えば、上の表を時間順に並べたいとする: + +```{r, purl=TRUE} +rna %>% + count(infection, time) %>% + arrange(time) +``` + +あるいは回数で: + +```{r, purl=TRUE} +rna %>% + count(infection, time) %>% + arrange(n) +``` + +降順にソートするには、`desc()`関数を追加する必要がある: + +```{r, purl=TRUE} +rna %>% + count(infection, time) %>% + arrange(desc(n)) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ + +1. 各サンプルで分析された遺伝子の数は? +2. group_by()`と `summarise()\\`を使用して、各サンプルのシーケンス深度(全カウントの合計)を評価する。 シーケンス深度が最も深いサンプルはどれですか? シーケンス深度が最も深いサンプルはどれですか? +3. サンプルを1つ選び、バイオタイプ別に遺伝子数を評価する。 +4. DNAメチル化異常」という表現型に関連する遺伝子を特定し、時間0、時間4、時間8における平均発現量(対数)を計算する。 + +::::::::::::::: solution + +## ソリューション + +```{r} +## +rna %>% + count(sample) +## 2. +rna %>% + group_by(sample) %>% + summary(seq_depth = sum(expression)) %>% + arrange(desc(seq_depth)) +## 3. +rna %>% + filter(sample == "GSM2545336") %>% + count(gene_biotype) %>% + arrange(desc(n)) +## 4. +rna %>% + filter(phenotype_description == "abnormal DNA methylation") %>% + group_by(gene, time) %>% + summary(mean_expression = mean(log(expression)) %>% + arrange() +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## データの再構築 + +rna`tibble の行には、`gene`と`sample\\` という2つの変数の組み合わせに関連付けられた発現値(単位)が格納されている。 + +比較を容易にするために、結果を並べ替えると便利なことがある。 +arrange()\\`を使って表を並べ替えることができる。 +例えば、上の表を時間順に並べたいとする: または遺伝子(gene_biotype, ENTREZ_ID, product, ...)。 +その他の列はすべて、 +(生物、年齢、性別、...)のいずれかを記述する変数に対応している。 または遺伝子(gene_biotype, ENTREZ_ID, product, ...)。 +遺伝子やサンプルによって変化しない変数は、すべての行で同じ値を持つ。 + +```{r} +rna %>% + arrange(gene) +``` + +この構造は`long-format`と呼ばれ、1つのカラムにはすべての値、 +、もう1つのカラムには値のコンテキストが列挙されている。 + +場合によっては、`long-format`は実際には "human-readable "ではなく、別のフォーマット、 +`wide-format`がよりコンパクトにデータを表現する方法として好まれる。 +これは通常、科学者が +、行が遺伝子、列がサンプルを表す行列として見るのに慣れている遺伝子発現値の場合である。 +これは通常、科学者が +、行が遺伝子、列がサンプルを表す行列として見るのに慣れている遺伝子発現値の場合である。 + +このフォーマットでは、 +、サンプル内の遺伝子発現レベルとサンプル間の遺伝子発現レベル +の関係を調べることができる。 + +```{r, echo=FALSE} +rna %>% + select(gene, sample, expression) %>% + pivot_wider(names_from = sample, + values_from = expression) +``` + +rna`の遺伝子発現値をワイドフォーマットに変換するには、 +、`sample\\`カラムの値が +、カラム変数の名前になる新しいテーブルを作成する必要がある。 + +ここでの重要なポイントは、我々はまだ +、整然としたデータ構造に従っているが、 +、興味のある観察に従ってデータを**整形**したということである:遺伝子ごと、サンプルごとに記録する代わりに、遺伝子ごとの発現レベル +。 + +逆の変換は、列名を新しい変数の値( +)に変換することである。 + +`pivot_longer()` と `pivot_wider()` の2つの `tidyr` 関数を使って、これらの変換を行うことができます( +[こちら](https://tidyr.tidyverse.org/dev/articles/pivot.html) を参照してください)( +)。 + +### より広いフォーマットへのデータのピボット + +rna`の最初の3列を選択し、`pivot_wider()\\` +を使ってデータをワイドフォーマットに変換してみよう。 + +```{r, purl=TRUE} +rna_exp <- rna %>% + select(gene, sample, expression) +rna_exp +``` + +pivot_wider\\`は主に3つの引数を取る: + +1. 変換されるデータ; +2. the `names_from` : その値が新しいカラム + の名前になるカラム; +3. value_from\\`: 新しいカラム + を埋める値。 + +```{r, fig.cap="Wide pivot of the `rna` data.", echo=FALSE, message=FALSE} +knitr::include_graphics("fig/pivot_wider.png") + +``` + +```{r, purl=TRUE} +rna_wide <- rna_exp %>% + pivot_wider(names_from = sample, + values_from = expression) +rna_wide +``` + +デフォルトでは、`pivot_wider()` 関数は欠損値に対して `NA` を追加することに注意してください。 + +何らかの理由で、あるサンプルで +、いくつかの遺伝子の発現値が欠落していたとしよう。 何らかの理由で、あるサンプルで +、いくつかの遺伝子の発現値が欠落していたとしよう。 以下の架空の例では、遺伝子Cyp2d22の発現値はGSM2545338サンプルの +。 + +```{r, purl=TRUE} +rna_with_missing_values <- rna %>% + select(gene, sample, expression) %>% + filter(gene %in% c("Asl", "Apod", "Cyp2d22")) %>% + filter(sample %in% c("GSM2545336", "GSM2545337", "GSM2545338")) %>% + arrange(sample) %>% + filter(!(gene == "Cyp2d22" & sample != "GSM2545338")) +rna_with_missing_values +``` + +デフォルトでは、`pivot_wider()`関数は、 +の値が見つからない場合に `NA` を追加する。 これは、 +`pivot_wider()` 関数の `values_fill` 引数でパラメータ化できる。 summarise()\\`関数 + +```{r, purl=TRUE} +rna_with_missing_values %>% + pivot_wider(names_from = sample, + values_from = expression) + +rna_with_missing_values %>% + pivot_wider(names_from = sample, + values_from = expression, + values_fill = 0) +``` + +### データを長いフォーマットにピボットする + +逆の状況では、カラム名を使い、 +、新しい変数のペアに変えている。 一方の変数はカラム名を +の値で表し、もう一方の変数にはカラム名に関連付けられている以前の値 +が格納されている。 一方の変数はカラム名を +の値で表し、もう一方の変数にはカラム名に関連付けられている以前の値 +が格納されている。 + +pivot_longer()\\`は主に4つの引数を取る: + +1. 変換されるデータ; +2. names_to\\`: + の現在のカラム名で作成したい新しいカラム名; +3. value_to\\`: 作成したい新しいカラム名で、 + の現在の値を格納する; +4. 変数 `names_to` と + `values_to` に格納する(または削除する)列の名前。 + +```{r, fig.cap="`rna`データのロングピボット。", echo=FALSE, message=FALSE} +knitr::include_graphics("fig/pivot_longer.png") + +``` + +rna_wide`から`rna_long`を再作成するには、 +`sample`というキーと`expression`という値を作成し、`gene`以外のすべてのカラム +。ここでは、`gene`カラム +をマイナス記号で削除する。 + +ここで、新しい変数名がどのように引用されるかに注目してください。 + +{r} +rna_long<- rna_wide %>% + pivot_longer(names_to = "sample", + values_to = "expression", + -gene) +rna_long +``` + +また、 +、どのようなカラムを含めるかという指定も使えたはずだ。 これは、 +のカラムが多数あり、 +のままにしておくよりも、何を集めるかを指定する方が簡単な場合に便利である。 また、 +、どのようなカラムを含めるかという指定も使えたはずだ。 これは、 +のカラムが多数あり、 +のままにしておくよりも、何を集めるかを指定する方が簡単な場合に便利である。 ここで、`starts_with()`関数を使えば、 +のサンプル名をすべてリストアップすることなく取得することができる! +もう一つの可能性は `:` 演算子を使うことである! +もう一つの可能性は `:` 演算子を使うことである! + +```{r} +rna_wide %>% + pivot_longer(names_to = "sample", + values_to = "expression", + cols = starts_with("GSM")) +rna_wide %>% + pivot_longer(names_to = "sample", + values_to = "expression", + GSM2545336:GSM2545380) +``` + +ワイドフォーマットで欠損値があった場合、新しいロングフォーマットでは`NA`が +。 + +前回の欠損値を含む架空のティブルを思い出してほしい: + +```{r} +rna_with_missing_values + +wide_with_NA<- rna_with_missing_values %>% + pivot_wider(names_from = sample, + values_from = expression) +wide_with_NA + +wide_with_NA %>% + pivot_longer(names_to = "sample", + values_to = "expression", + -gene) +``` + +より幅の広い、より長いフォーマットへの移行は、データセットのバランスをとるのに有効な方法である。 +、どの複製も同じ構成になる。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## 質問 + +マウス遺伝子の中にはヒトにホモログがないものもある。 これらは、 +`filter()` と、 +何かが `NA` かどうかを判定する `is.na()` 関数を使って取得することができる。 +rnaテーブルから始めて、`pivot_wider()`関数を使用して、 +、各マウスの遺伝子発現レベルを示すワイドフォーマットのテーブルを作成する。 +そして、`pivot_longer()`関数を使って、ロングフォーマットの表を復元する。 + +::::::::::::::: solution + +## ソリューション + +```{r, answer=TRUE, purl=TRUE} +rna1<- rna %>% +select(gene, mouse, expression) %>% +pivot_wider(names_from = mouse, values_from = expression) +rna1 + +rna1 %>% +pivot_longer(names_to = "mouse_id", values_to = "counts", -gene) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## 質問 + +rna`データフレームから X 染色体と Y 染色体に位置する遺伝子をサブセットし、`sex` を列、`chromosome_name\\` を +行、各染色体に位置する遺伝子の平均発現量を値として、 +以下のようにデータフレームを広げる: + +```{r, echo=FALSE, message=FALSE} +knitr::include_graphics("fig/Exercise_pivot_W.png") +``` + +整形する前にまとめる必要がある! + +::::::::::::::: solution + +## ソリューション + +まず、 +男性と女性のサンプルから、XとYの連鎖遺伝子の平均発現量を計算してみよう... + +```{r} + rna %>% + filter(chromosome_name == "Y" | chromosome_name == "X") %>% + group_by(sex, chromosome_name) %>% + summise(mean = mean(expression)) +``` + +そして、表をワイドフォーマットにピボットする + +```{r, answer=TRUE, purl=TRUE} +rna_1<- rna %>% + filter(chromosome_name == "Y" | chromosome_name == "X") %>% + group_by(sex, chromosome_name) %>% + summise(mean = mean(expression)) %>% + pivot_wider(names_from = sex, + values_from = mean) + +rna_1 +``` + +各行が一意な `chromosome_name` と `gender` の組み合わせになるように、このデータフレームを `pivot_longer()` で変換する。 + +```{r, answer=TRUE, purl=TRUE} +rna_1 %>% + pivot_longer(names_to = "gender", + values_to = "mean", + -chromosome_name) + +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## 質問 + +rna\\`データセットを使って、 +各行が遺伝子の平均発現量を表し、 +各列が異なるタイムポイントを表す発現行列を作成する。 + +::::::::::::::: solution + +## ソリューション + +まず、遺伝子別、時間別の平均発現量を計算してみよう。 + +```{r} +rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) +``` + +pivot_wider()関数を使用する前に + +```{r} +rna_time<- rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) +rna_time +``` + +これにより、数字で始まるカラム名を持つティブルが生成されることに注意。 +これにより、数字で始まるカラム名を持つティブルが生成されることに注意。 +タイムポイントに対応するカラムを選択したい場合、 +、カラム名を直接使うことはできない。 列4を選択するとどうなるか? 列4を選択するとどうなるか? + +```{r} +rna %>% + group_by(gene, time) %>% + summary(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) %>% + select(gene, 4) +``` + +タイムポイント4を選択するには、"˶\\`" というバックスティックを付けたカラム名を引用しなければならない。 + +```{r} +rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) %>% + select(gene, `4`) +``` + +、数字で始まらない名前を選択する: + +```{r} +rna %>% + group_by(gene, time) %>% + summary(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) %>% + rename("time0" = `0`, "time4" = `4`, "time8" = `8`) %>% + select(gene, time4) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## 質問 + +タイムポイントごとの平均発現レベルを含む前のデータフレームを使用し、 +、タイムポイント8とタイムポイント0の間のfold-changes、およびタイムポイント8とタイムポイント4の間のfold-changes +を含む新しい列を作成する。 +この表を、計算されたフォールド・チェンジを集めたロングフォーマットの表に変換する。 +この表を、計算されたフォールド・チェンジを集めたロングフォーマットの表に変換する。 + +::::::::::::::: solution + +## ソリューション + +rna_time tibbleから開始する: + +```{r} +rna_time +``` + +フォールドチェンジを計算する: + +```{r} +rna_time %>% + mutate(time_8_vs_0 = `8` / `0`, time_8_vs_4 = `8` / `4`) +``` + +そして、pivot_longer()関数を使用する: + +```{r} +rna_time %>% + mutate(time_8_vs_0 = `8` / `0`, time_8_vs_4 = `8` / `4`) %>% + pivot_longer(names_to = "comparisons", + values_to = "Fold_changes", + time_8_vs_0:time_8_vs_4) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## テーブルの結合 + +実生活の多くの場面で、データは複数のテーブルにまたがっている。 +通常このようなことが起こるのは、異なる情報源から異なるタイプの情報が +収集されるからである。 +通常このようなことが起こるのは、異なる情報源から異なるタイプの情報が +収集されるからである。 + +分析によっては、2つ以上のテーブル( +)のデータを、すべてのテーブルに共通するカラム( +)に基づいて1つのデータフレームにまとめることが望ましい場合がある。 + +dplyr\\` パッケージは、指定されたカラム内のマッチに基づいて、2つの +データフレームを結合するための結合関数のセットを提供する。 ここでは、 +、結合について簡単に紹介する。 詳しくは、 +テーブル +ジョインの章を参照されたい。 +データ変換チート +シート +、テーブル結合に関する簡単な概要も提供している。 ここでは、 +、結合について簡単に紹介する。 詳しくは、 +テーブル +ジョインの章を参照されたい。 +データ変換チート +シート +、テーブル結合に関する簡単な概要も提供している。 + +、元の`rna`テーブルをサブセットして作成し、 +、3つのカラムと10行だけを残す。 + +```{r} +rna_mini<- rna %>% + select(gene, sample, expression) %>% + head(10) +rna_mini +``` + +2番目のテーブル`annot1`には、遺伝子と +gene_descriptionの2つのカラムがある。 2番目のテーブル`annot1`には、遺伝子と +gene_descriptionの2つのカラムがある。 +[download annot1.csv](https://carpentries-incubator.github.io/bioc-intro/data/annot1.csv) +リンクをクリックして`data/`フォルダに移動するか、 +以下のRコードを使って直接フォルダにダウンロードすることができる。 + +```{r, message=FALSE} +download.file(url = "https://carpentries-incubator.github.io/bioc-intro/data/annot1.csv", + destfile = "data/annot1.csv") +annot1 <- read_csv(file = "data/annot1.csv") +annot1 +``` + +ここで、`dplyr` パッケージの `full_join()` 関数を使用して、これら2つのテーブルを、すべての +変数を含む1つのテーブルに結合したいと思います。 +関数は、最初のテーブルと2番目のテーブルの列 +に一致する共通変数を自動的に見つける。 この場合、`gene`は共通の +。 このような変数をキーと呼ぶ。 キーは、 +オブザベーションを異なるテーブル間でマッチさせるために使用される。 +関数は、最初のテーブルと2番目のテーブルの列 +に一致する共通変数を自動的に見つける。 この場合、`gene`は共通の +。 このような変数をキーと呼ぶ。 キーは、 +オブザベーションを異なるテーブル間でマッチさせるために使用される。 + +```{r} +full_join(rna_mini, annot1) +``` + +実生活では、遺伝子アノテーションのラベルが異なることがある。 + +annot2`テーブルは、遺伝子名を含む +変数のラベルが異なる以外は、`annot1`と全く同じである。 この場合も、 [download annot2.csv](https://carpentries-incubator.github.io/bioc-intro/data/annot2.csv) +、自分で`data/\`に移動するか、以下のRコードを使う。 この場合も、 [download annot2.csv](https://carpentries-incubator.github.io/bioc-intro/data/annot2.csv) +、自分で`data/\`に移動するか、以下のRコードを使う。 + +```{r, message=FALSE} +download.file(url = "https://carpentries-incubator.github.io/bioc-intro/data/annot2.csv", + destfile = "data/annot2.csv") +annot2 <- read_csv(file = "data/annot2.csv") +annot2 +``` + +どの変数名も一致しない場合、マッチングに使用する +変数を手動で設定することができる。 どの変数名も一致しない場合、マッチングに使用する +変数を手動で設定することができる。 これらの変数は、`rna_mini` と `annot2` テーブルを使用して以下に示すように、 +`by` 引数を使用して設定することができる。 + +```{r} +full_join(rna_mini, annot2, by = c("gene" = "external_gene_name")) +``` + +上で見たように、最初のテーブルの変数名は、結合されたテーブルでも +。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジだ: + +[こちら](https://carpentries-incubator.github.io/bioc-intro/data/annot3.csv) +をクリックして `annot3` テーブルをダウンロードし、そのテーブルをあなたの data/ リポジトリに置いてください。 full_join()`関数を使用して、テーブル`rna_mini`と`annot3\` を結合する。 +、遺伝子_Klk6_、_mt-Tf_、_mt-Rnr1_、_mt-Tv_、_mt-Rnr2_、_mt-Tl1_はどうなったのか? full_join()` +関数を使用して、テーブル `rna_mini` と `annot3` を結合する。 +、遺伝子_Klk6_、_mt-Tf_、_mt-Rnr1_、_mt-Tv_、_mt-Rnr2_、_mt-Tl1_はどうなったのか? + +::::::::::::::: solution + +## ソリューション + +```{r, message=FALSE} +annot3 <- read_csv("data/annot3.csv") +full_join(rna_mini, annot3) +``` + +遺伝子_Klk6_は`rna_mini`にのみ存在し、遺伝子_mt-Tf_、_mt-Rnr1_、_mt-Tv_、 +_mt-Rnr2_、_mt-Tl1_は`annot3`テーブルにのみ存在する。 表の +変数のそれぞれの値は、欠損として符号化されている。 表の +変数のそれぞれの値は、欠損として符号化されている。 + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## データのエクスポート + +dplyr\\`を使って、 +から情報を抽出したり、生データを要約したりする方法を学んだので、これらの新しいデータセットをエクスポートして、 +を共同研究者と共有したり、アーカイブしたりしたいと思うかもしれない。 + +RにCSVファイルを読み込むために使用される `read_csv()` 関数と同様に、 +、データフレームからCSVファイルを生成する `write_csv()` 関数があります。 + +write_csv()`を使う前に、生成されたデータセットを格納する新しいフォルダ `data_output` +を作業ディレクトリに作成する。 +、生成されたデータセットを生データと同じディレクトリに書き込みたくない。 +別々にするのは良い習慣だ。 data`フォルダーには、 +、変更されていない生のデータだけを入れておく。 +、削除したり変更したりしないように、そのままにしておく。 対照的に、このスクリプトは`data_output` +ディレクトリの内容を生成するので、そこに含まれるファイルが削除されても、 +再生成することができる。 +、生成されたデータセットを生データと同じディレクトリに書き込みたくない。 +別々にするのは良い習慣だ。 data`フォルダーには、 +、変更されていない生のデータだけを入れておく。 +、削除したり変更したりしないように、そのままにしておく。 対照的に、このスクリプトは`data_output\` +ディレクトリの内容を生成するので、そこに含まれるファイルが削除されても、 +再生成することができる。 + +write_csv()\\`を使用して、以前に作成したrna_wideテーブルを保存しよう。 + +```{r, purl=TRUE, eval=FALSE} +write_csv(rna_wide, file = "data_output/rna_wide.csv") +``` + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- tidyverseメタパッケージを使用したRでの表形式データ + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/ja/episodes/40-visualization.Rmd b/locale/ja/episodes/40-visualization.Rmd new file mode 100644 index 000000000..2e91975fa --- /dev/null +++ b/locale/ja/episodes/40-visualization.Rmd @@ -0,0 +1,1093 @@ +--- +source: Rmd +title: データの可視化 +teaching: 60 +exercises: 60 +--- + +```{r loaddata_vis, echo=FALSE, purl=FALSE, message=FALSE} +if (!file.exists("data/rnaseq.csv")) +download.file(url = "https://github.com/carpentries-incubator/bioc-intro/raw/main/episodes/data/rnaseq.csv", + destfile = "data/rnaseq.csv") +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- ggplotを使って散布図、箱ひげ図、折れ線グラフなどを作成する。 +- ユニバーサルプロット設定を行う。 +- ファセットとは何かを説明し、ggplotでファセットを適用する。 +- 既存のggplotプロットの美学(軸ラベルや色を含む)を修正する。 +- データフレーム内のデータから複雑でカスタマイズされたプロットを作成。 + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- Rによる可視化 + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +```{r vis_setup, echo=FALSE} +rna <- read.csv("data/rnaseq.csv") +``` + +> このエピソードは、Data Carpentriesの_Data Analysis and +> Visualisation in R for Ecologists_レッスンに基づいています。 + +## データの可視化 + +必要なパッケージをロードすることから始める。 \*\*ggplot2`**は、 **tidyverse`\*\*パッケージに含まれています。 + +```{r load-package, message=FALSE, purl=TRUE} +library("tidyverse") +``` + +ワークスペースにまだない場合は、前回の +レッスンで保存したデータをロードします。 + +```{r load-data, eval=FALSE, purl=TRUE} +rna <- read.csv("data/rnaseq.csv") +``` + +Data Visualization Cheat +Sheet](https://raw.githubusercontent.com/rstudio/cheatsheets/main/data-visualization.pdf) +は `ggplot2` の基本からより高度な機能までをカバーし、 +パッケージで利用可能な多くのデータ表現 +の概要を理解するためのリマインダとしてだけでなく、手助けになるでしょう。 Thomas Lin Pedersen氏による以下のビデオ +チュートリアル([パート1](https://www.youtube.com/watch?v=h29g21z0a68)と +[2](https://www.youtube.com/watch?v=0m4yywqNPVY)) +も非常に参考になる。 + +## ggplot2\`によるプロット + +ggplot2`は、データフレーム内のデータから複雑な +プロットを簡単に作成できるプロットパッケージである。 どの変数をプロットするか、どのように表示するか、 +、一般的なビジュアル・プロパティを指定するための、よりプログラム的な +。 +`ggplot2\`を支える理論的基盤は、_Grammar of Graphics_ (@Wilkinson:2005)である。 この +アプローチを使用すると、基礎となるデータが変更された場合、または棒グラフから散布図に変更することを決めた場合に +、最小限の変更で済む。 これは、 +、最小限の調整で出版品質のプロットを作成するのに役立ちます +、微調整。 + +ggplot2`に関する本(@ggplot2book)があり、 +。 第3版は現在準備中で、 [オンラインで自由に利用できる](https://ggplot2-book.org/)。 +の `ggplot2\` ウェブページ([https://ggplot2.tidyverse.org](https://ggplot2.tidyverse.org))に十分なドキュメントがあります。 + +ggplot2`の関数は、'long'形式のデータ、つまり、 +すべての次元を表す列と、すべてのオブザベーションを表す行を持つ。 よく構造化されたデータ +、 `ggplot2\`で図を作成する時間を大幅に節約できる。 + +ggplotグラフィックスは、新しい要素を追加することによって段階的に構築される。 この方法で +レイヤーを追加すると、プロットの広範な柔軟性と +カスタマイズが可能になる。 + +> Grammar of Graphicsの背後にある考え方は、同じ3つのコンポーネントからすべての +> グラフを構築できるということである:(1)データセット、(2)座標系、 +> 、(3)ジオム、つまりデータ点を表す視覚的マーク [^three_comp_ggplot2] である。 + +[^three_comp_ggplot2]: 出典[データ可視化チートシート](https://raw.githubusercontent.com/rstudio/cheatsheets/main/data-visualization.pdf). + +ggplotを構築するために、 +、さまざまなタイプのプロットに使用できる以下の基本テンプレートを使用する: + +``` +ggplot(data =, mapping = aes()) +() +``` + +- ggplot()`関数を使用し、`data\`引数を使用して特定の**data + frame**にプロットをバインドする。 + +```{r, eval=FALSE} +ggplot(data = rna) +``` + +- (`aes`)関数を使用して)**マッピング**を定義する。 + 、プロットする変数を選択し、 + 、x/yの位置や、 + 、サイズ、形、色などの特徴として、グラフでどのように表示するかを指定する。 + +```{r, eval=FALSE} +ggplot(data = rna, mapping = aes(x = expression)) +``` + +- 追加 '**geoms**' - ジオメトリ、つまりプロット内の + データのグラフ表現(点、線、棒)。 ggplot2\`は多くの + 、様々なジオムを提供している: + + ``` + * 散布図やドットプロットなどには `geom_point()` を使用する。 + * + * `geom_boxplot()` ボックスプロット! + * トレンドライン、時系列など。 + ``` + +プロットにgeom(etry)を追加するには `+` 演算子を使います。 +`geom_histogram()` をまず使ってみよう: + +```{r first-ggplot, cache=FALSE, purl=TRUE} +ggplot(data = rna, mapping = aes(x = expression)) + + geom_histogram() +``` + +ggplot2`パッケージの`+`は特に便利で、 +、既存の`ggplot\`オブジェクトを修正することができる。 つまり、 +、プロット・テンプレートを簡単に設定し、 +、さまざまなタイプのプロットを便利に調べることができる: + +```{r, eval=FALSE, purl=TRUE} +# Assign plot to a variable +rna_plot <- ggplot(data = rna, + mapping = aes(x = expression)) + +# Draw the plot +rna_plot + geom_histogram() +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ + +ヒストグラムを描画するときに表示される自動メッセージにお気づきでしょう: + +```{r, echo=FALSE, fig.show="hide"} +ggplot(rna, aes(x = expression)) + + geom_histogram() +``` + +geom_histogram()`の引数`bins`または`binwidth\` を変更して、 +ビンの数または幅を変更する。 + +::::::::::::::: solution + +## ソリューション + +```{r, purl=TRUE} +# change bins +ggplot(rna, aes(x = expression)) + + geom_histogram(bins = 15) + +# change binwidth +ggplot(rna, aes(x = expression)) + + geom_histogram(binwidth = 2000) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +データが右に偏っていることがわかる。 より対称的な分布にするために、 +log2変換を適用することができる。 ここでは、 +、0に等しい式の値に対して返される`-Inf`値 +を避けるために、小さな定数値(`+1`)を追加していることに注意してください。 + +```{r log-transfo, cache=FALSE, purl=TRUE} +rna<- rna %>% + mutate(expression_log = log2(expression + 1)) +``` + +ここで対数変換した式のヒストグラムを描いてみると、 +の分布は確かに正規分布に近くなっている。 + +```{r second-ggplot, cache=FALSE, purl=TRUE} +ggplot(rna, aes(x = expression_log)) + geom_histogram() +``` + +これからは対数変換した発現値を扱うことにする。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ + +この変換を視覚化するもう1つの方法は、オブザベーションのスケール +を考えることである。 たとえば、 +プロットの空間でオブザベーションをよりよく分布させるために、軸のスケール +を変更する価値があるかもしれません。 軸のスケールの変更は、 +他のコンポーネントの追加/変更と同様に(すなわち、 +コマンドをインクリメンタルに追加することによって)行われます。 このように変更してみてほしい: + +- `scale_x_log10()` を参照。 前のグラフと比較してみよう。 + 、警告メッセージが表示されるようになったのはなぜですか? + +::::::::::::::: solution + +## ソリューション + +```{r, eval=TRUE, purl=TRUE, echo=TRUE} +ggplot(data = rna,mapping = aes(x = expression))+ + geom_histogram() + + scale_x_log10() +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +**注**\*。 + +- ggplot()`関数で設定したものはすべて、あなたが追加したgeom + レイヤーで見ることができます(つまり、これらはグローバルなプロット設定です)。 この + には、`aes()\`で設定したx軸とy軸のマッピングが含まれる。 +- また、`ggplot()`関数でグローバルに定義された + マッピングとは別に、与えられたジオムに対するマッピングを指定することもできます。 +- 新しいレイヤーを追加するために使われる`+`記号は、_前の_レイヤーを含む + 行の最後に置かなければなりません。 その代わりに、`+`記号が + 新しいレイヤーを含む行の先頭に追加された場合、 + `ggplot2` は新しいレイヤーを追加せず、エラー + メッセージを返す。 + +```{r, eval=FALSE} +# これはレイヤーを追加するための正しい構文です +rna_plot + + geom_histogram() + +# これは新しいレイヤーを追加せず、エラーメッセージを返します +rna_plot + + geom_histogram() +``` + +## 反復的にプロットを構築する + +ここでは、2つの連続変数と +`geom_point()`関数を使って散布図を描きます。 このグラフは、時間8と時間0、時間4と時間0を比較した発現のlog2倍変化 +。 +この目的のために、まず対数変換した +発現値の平均値を遺伝子ごと、時間ごとに計算する必要がある。次に、 +、時間8と時間0の間の平均対数発現と、 +、時間4と時間0の間の平均対数発現を差し引くことにより、対数倍変化を計算する。 ここでは、後で遺伝子を表現するために使用する遺伝子 +バイオタイプも含めていることに注意されたい。 +フォールドの変化を `rna_fc.` という新しいデータフレームに保存する。 + +```{r rna_fc, cache=FALSE, purl=TRUE} +rna_fc <- rna %>% select(gene, time, + gene_biotype, expression_log) %>% + group_by(gene, time, gene_biotype) %>% + summarize(mean_exp = mean(expression_log)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) %>% + mutate(time_8_vs_0 = `8` - `0`, time_4_vs_0 = `4` - `0`) + +``` + +新しく作成されたデータセット `rna_fc` を使って ggplot を作成することができる。 +ggplot2\`でプロットを作成するのは、通常、反復的なプロセスである。 +まず、使用するデータセットを定義し、軸を配置し、 +ジオムを選択する: + +```{r create-ggplot-object, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point() +``` + +次に、このプロットからより多くの情報を抽出するために、プロットを修正し始める。 +例えば、オーバープロットを避けるために透明度(`α`)を加えることができる: + +```{r adding-transparency, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point(alpha = 0.3) +``` + +また、すべてのポイントに色を付けることもできる: + +```{r adding-colors, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point(alpha = 0.3, color = "blue") +``` + +あるいは、プロット中の各遺伝子を異なる色にするために、 +、引数**color**の入力としてベクトルを使うこともできる。 ggplot2`は、ベクトルの異なる値に対応する異なる +。 以下は、 +`gene_biotype\`を使った例である: + +```{r color-by-gene_biotype1, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point(alpha = 0.3, aes(color = gene_biotype)) + +``` + +また、 +`ggplot()`関数で提供されるマッピングの中で直接色を指定することもできる。 これはどのジオムレイヤーでも見ることができ、 +のマッピングは `aes()` で設定したx軸とy軸によって決定される。 + +```{r color-by-gene_biotype2, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0, + color = gene_biotype)) + + geom_point(alpha = 0.3) +``` + +最後に、`geom_abline()` +: + +```{r adding-diag, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0, + color = gene_biotype)) + + geom_point(alpha = 0.3) + + geom_abline(intercept = 0) +``` + +ジオムレイヤーを `geom_point` から +`geom_jitter` に変更しても、色は `gene_biotype` によって決定されることに注意してください。 + +```{r color-by-gene_biotype3, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0, + color = gene_biotype)) + + geom_jitter(alpha = 0.3) + + geom_abline(intercept = 0) +``` + +```{r, echo=FALSE, message=FALSE} +library("hexbin") +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ + +散布図は、小規模なデータセットの探索に役立つツールである。 rna_fc\` +データセットのような多数のオブザベーションを持つ +データセットの場合、点のオーバープロットは散布図の制限となりうる。 +このような設定を扱うための1つの戦略は、 +の観測値を六角形にビニングすることである。 プロット空間は六角形にテッセレーションされている。 それぞれの +六角形は、 +その境界内に入るオブザベーションの数に基づいて色が割り当てられる。 + +- ggplot2`で六角ビニングを使用するには、まずRパッケージ + `hexbin\`をCRANからインストールしてロードする。 + +- そして、`geom_hex()`関数を使ってhexbin図を作成する。 + +- 散布図と比較して、六角形のビン + プロットの相対的な長所と短所は何か? 上記の散布図( + )を調べ、作成した六角形のビンプロットと比較する。 + +::::::::::::::: solution + +## ソリューション + +```{r, eval=FALSE, purl=TRUE} +install.packages("hexbin") +``` + +```{r, purl=TRUE} +library("hexbin") + +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_hex() + + geom_abline(intercept = 0) + +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ + +今学んだことを使って、`rna`データセットから`sample`に対する`expression_log` +の散布図を作成し、 +異なる色で時間を表示する。 このようなデータを表示するのは良い方法ですか? + +::::::::::::::: solution + +## ソリューション + +```{r, eval=TRUE, purl=TRUE} +ggplot(data = rna, mapping = aes(y = expression_log, x = sample)) + + geom_point(aes(color = time)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## ボックスプロット + +ボックスプロットを使って、各サンプル内の遺伝子発現の分布( +)を可視化することができる: + +```{r boxplot, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_boxplot() +``` + +boxplotにポイントを追加することで、 +の測定数とその分布をよりよく知ることができる: + +```{r boxplot-with-points, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_jitter(alpha = 0.2, color = "tomato") + + geom_boxplot(alpha = 0) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ + +ボックスプロットレイヤーがジッターレイヤーの前にあることに注目してほしい。 +、ボックスプロットをポイントの下に配置するために、コードのどこを変更する必要がありますか? + +::::::::::::::: solution + +## ソリューション + +この2つのジオムの順番を入れ替えるべきだ: + +```{r boxplot-with-points2, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample))+ + geom_boxplot(alpha = 0) + + geom_jitter(alpha = 0.2, color = "tomato") +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +X軸の値がまだ正しく +読めないことにお気づきかもしれない。 ラベルの向きを変え、 +縦と横に重ならないように調整しよう。 +90度の角度を使ってもいいし、 +斜め向きのラベルに適切な角度を見つけるために実験してもいい: + +```{r boxplot-xaxis-rotated, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample))+ + geom_jitter(alpha = 0.2, color = "tomato") + + geom_boxplot(alpha = 0) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ + +感染期間( +)に応じて、箱ひげ図上のデータ点に色を付ける(`time`)。 + +_ヒント:_ `time`のクラスをチェックする。 +`time` のクラスをggplotマッピングで整数から因数に直接変更することを検討する。 +、Rのグラフの作り方が変わるのはなぜですか? + +::::::::::::::: solution + +## ソリューション + +```{r boxplot-color-time, cache=FALSE, purl=TRUE} +# time as integer +ggplot(data = rna, + mapping = aes(y = expression_log, + x = sample))+ + geom_jitter(alpha = 0.2, aes(color = time))+ + geom_boxplot(alpha = 0) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) + +# time as factor +ggplot(data = rna, + mapping = aes(y = expression_log, + x = sample))+ + geom_jitter(alpha = 0.2, aes(color = as.factor(time)))+ + geom_boxplot(alpha = 0) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ + +箱ひげ図は便利な要約だが、 +分布の_形_を隠してしまう。 例えば、分布が二峰性であれば、 +、ボックスプロットではそれを見ることはできない。 箱ひげ図に代わるものとして、(点の密度の)形状を描くバイオリン +プロットがある。 + +- geom_violin()`を参照してください。 + 引数 `fill\` の時間に従ってヴァイオリンにフィルを入れる。 + +::::::::::::::: solution + +## ソリューション + +```{r, eval=TRUE, echo=TRUE, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample))+ + geom_violin(aes(fill = as.factor(time)))+ + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ + +- ヴァイオリンのプロットを修正し、ヴァイオリンを `sex` で埋める。 + +::::::::::::::: solution + +## ソリューション + +```{r, eval=TRUE, echo=TRUE, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample))+ + geom_violin(aes(fill = sex))+ + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## 線プロット + +時刻8と +時刻0を比較し、log fold変化が最も大きかった10の遺伝子について、感染期間ごとの平均発現量を計算してみよう。 まず、遺伝子を選択し、選択した10遺伝子を含む`sub_rna`と呼ばれる`rna` +のサブセットを作成する必要がある。次に、 +データをグループ化し、各グループ内の平均遺伝子発現を計算する必要がある: + +```{r, purl=TRUE} +rna_fc<- rna_fc %>% arrange(desc(time_8_vs_0)) + +genes_selected <- rna_fc$gene[1:10] + +sub_rna<- rna %>% + filter(gene %in% genes_selected) + +mean_exp_by_time<- sub_rna %>% + group_by(gene,time) %>% + summarize(mean_exp = mean(expression_log)) + +mean_exp_by_time +``` + +X軸に感染期間( +)、Y軸に平均発現をとって折れ線グラフを作成することができる: + +```{r first-time-series, purl=TRUE} +ggplot(data = mean_exp_by_time, mapping = aes(x = time, y = mean_exp))+ + geom_line() +``` + +残念なことに、これはうまくいかない。というのも、 +の全遺伝子のデータをまとめてプロットしたからである。 各遺伝子に対して線を引くようにggplotに指示する必要がある。 +、`group = gene`を含むようにesthetic関数を修正する: + +```{r time-series-by-gene, purl=TRUE} +ggplot(data = mean_exp_by_time, + mapping = aes(x = time, y = mean_exp, group = gene))+ + geom_line() +``` + +色をつければ、プロットの中で遺伝子を区別できるようになる( +`color`を使えば、自動的にデータをグループ化することもできる): + +```{r time-series-with-colors, purl=TRUE} +ggplot(data = mean_exp_by_time, + mapping = aes(x = time, y = mean_exp, color = gene))+ + geom_line() +``` + +## ファセット + +ggplot2\`には_faceting_と呼ばれる特別なテクニックがあり、 +、データセットに含まれる +、1つのプロットを複数の(サブ)プロットに分割することができる。 こ れ ら の異な る サブプ ロ ッ ト は、 同 じ プ ロ パテ ィ +を継承 し ます (軸の限界、目盛り、 ...)。 直接比較しやすくするためだ。 +、これを用いて各遺伝子について時間軸に沿った折れ線グラフを作成する: + +```{r first-facet, purl=TRUE} +ggplot(data = mean_exp_by_time, + mapping = aes(x = time, y = mean_exp))+ geom_line() + + facet_wrap(~ gene) +``` + +ここでは、X軸とY軸はすべてのサブプロットで同じスケールになっている。、Y軸のスケールを自由に設定できるように`scales`を修正することで、このデフォルトの動作を変更することができる: + +```{r first-facet-scales, purl=TRUE} +ggplot(data = mean_exp_by_time, + mapping = aes(x = time, y = mean_exp))+ + geom_line() + + facet_wrap(~ gene, scales = "free_y") +``` + +ここで、各プロットの線をマウスの性別で分けたい。 +そのためには、 +、遺伝子、時間、性別でグループ化したデータフレームの平均発現を計算する必要がある: + +```{r data-facet-by-gene-and-sex, purl=TRUE} +mean_exp_by_time_sex<- sub_rna %>% + group_by(gene, time, sex) %>% + summarize(mean_exp = mean(expression_log)) + +mean_exp_by_time_sex +``` + +`color` を使ってさらに分割することで、ファセット化されたプロットを作ることができる(1つのプロット内で): + +```{r facet-by-gene-and-sex, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex))+ + geom_line() + + facet_wrap(~ gene, scales = "free_y") +``` + +通常、背景が白いプロットは印刷したときに読みやすくなる。 +、関数 `theme_bw()` を使って背景を白に設定することができる。 +さらに、グリッドを削除することもできる: + +```{r facet-by-gene-and-sex-white-bg, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex))+ + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ + +、各染色体の +平均発現量が感染期間を通じてどのように変化するかをプロットする。 + +::::::::::::::: solution + +## ソリューション + +```{r mean-exp-chromosome-time-series, purl=TRUE} +mean_exp_by_chromosome<- rna %>% + group_by(chromosome_name, time) %>% + summary(mean_exp = mean(expression_log)) + +ggplot(data = mean_exp_by_chromosome, mapping = aes(x = time, + y = mean_exp))+ + geom_line() + + facet_wrap(~ chromosome_name, scales = "free_y") +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +facet_wrap`ジオメトリは、1ページにきれいに収まるように、プロットを任意の数の +次元に抽出する。 一方、 +`facet_grid` ジオメトリでは、 +数式表記(`rows ~ columns`; `.\` +は、1つの行または列のみを示すプレースホルダとして使用できます)によって、プロットの配置方法を明示的に指定することができます。 + +先ほどのプロットを修正し、男性と女性の平均遺伝子発現 +が経時的にどのように変化したかを比較してみよう: + +```{r mean-exp-time-facet-sex-rows, purl=TRUE} +# 1列、行ごとのファセット +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = gene))+ + geom_line() + + facet_grid(sex ~ .) +``` + +```{r mean-exp-time-facet-sex-columns, purl=TRUE} +# 1行、列ごとのファセット +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = gene))+ + geom_line() + + facet_grid(. ~ sex) +``` + +## ggplot2\`テーマ + +`ggplot2` には、プロットの背景を白に変更する `theme_bw()` に加えて、 +手早く視覚化の見た目を変更するのに便利なテーマがいくつか用意されている。 +テーマの全リストは[https://ggplot2.tidyverse.org/reference/ggtheme.html](https://ggplot2.tidyverse.org/reference/ggtheme.html)で入手できる。 +theme_minimal()`や`theme_light()`は人気があり、`theme_void()\` +は新しい手作りのテーマを作る出発点として役に立つ。 + +ggthemes](https://jrnold.github.io/ggthemes/reference/index.html) +パッケージは様々なオプション(Excel 2003 +テーマを含む)を提供します。 `ggplot2` extensions +website](https://exts.ggplot2.tidyverse.org/) は、追加の +テーマを含む `ggplot2` の機能を拡張する +パッケージのリストを提供しています。 + +## カスタマイズ + +時間別、遺伝子別の平均発現のファセット・プロットに戻ろう。 +性別に色分けされている。 + +ggplot2\`のカンニング +シート](https://raw.githubusercontent.com/rstudio/cheatsheets/main/data-visualization.pdf), +を見て、プロットを改善する方法を考えてみてください。 + +ここで、軸の名前を +'time' や 'mean_exp' よりも情報量の多いものに変更し、図にタイトルを追加する: + +```{r mean_exp-time-with-right-labels, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex))+ + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + labs(title = "感染期間別の平均遺伝子発現", + x = "感染期間(日単位)", + y = "平均遺伝子発現") +``` + +軸にはより情報量の多い名前が付けられているが、フォントサイズを大きくすることで読みやすさは +: + +```{r mean_exp-time-with-right-labels-xfont-size, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex))+ + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + labs(title = "感染期間別の平均遺伝子発現", + x = "感染期間(日単位)", + y = "平均遺伝子発現") + + theme(text = element_text(size = 16)) +``` + +プロットのフォントを変更することも可能です。 +Windowsをお使いの場合は、 をインストールする必要があるかもしれません。 + +さらに、X軸とY軸のテキストの色、 +グリッドの色などをカスタマイズできる。 例えば、 +`legend.position`を`"top"`に設定することで、凡例を一番上に移動させることもできる。 + +```{r mean_exp-time-with-theme, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex))+ + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + labs(title = "感染期間別の平均遺伝子発現", + x = "感染期間(日単位)", + y = "平均遺伝子発現") + + theme(text = element_text(size = 16), + axis.text.x = element_text(color = "royalblue4", size = 12), + axis.text.y = element_text(color = "royalblue4", size = 12), + panel.grid = element_line(color="lightsteelblue1"), + legend.position = "top") +``` + +作成した変更がデフォルトのテーマよりも気に入った場合は、 +、オブジェクトとして保存して、作成した他の +プロットに簡単に適用することができます。 以下は、 +以前に作成したヒストグラムを使った例です。 + +```{r mean_exp-time-with-right-labels-xfont, cache=FALSE, purl=TRUE} +blue_theme <- theme(axis.text.x = element_text(colour = "royalblue4", + size = 12), + axis.text.y = element_text(colour = "royalblue4", + size = 12), + text = element_text(size = 16), + panel.grid = element_line(colour="lightsteelblue1")) + +ggplot(rna, aes(x = expression_log)) + + geom_histogram(bins = 20) + + blue_theme +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ + +これらの情報を手に入れたら、 +、この練習で作成したプロットのいずれかを改良するか、 +、あなた自身の美しいグラフを作成してください。 RStudio ggplot2 +を参考にしてください。 いくつかアイデアを挙げてみよう: + +- 線の太さを変えてみてください。 +- 伝説の名前を変える方法はありますか? + そのラベルについてはどうだろう? (ヒント: + `scale_` で始まる ggplot 関数を探す) +- 別のカラーパレットを使用するか、線の + カラーを手動で指定してみてください( + [http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/](https://www.cookbook-r.com/Graphs/Colors_\(ggplot2\)/) 参照)。 + +::::::::::::::: solution + +## ソリューション + +例えば、このプロットに基づくと + +```{r, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex))+ + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) +``` + +以下のようなカスタマイズが可能です: + +```{r, purl=TRUE} +# change the thickness of the lines +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line(size=1.5) + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + +# change the name of the legend and the labels +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + scale_color_discrete(name = "Gender", labels = c("F", "M")) + +# using a different color palette +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + scale_color_brewer(name = "Gender", labels = c("F", "M"), palette = "Dark2") + +# manually specifying the colors +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + scale_color_manual(name = "Gender", labels = c("F", "M"), + values = c("royalblue", "deeppink")) + +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## プロットの構成 + +ファセッティングは、1つのプロットを複数のサブプロットに分割するのに最適なツールです。 +しかし、 +複数の独立したプロット、すなわち異なる +変数、あるいは異なるデータフレームに基づくプロットを含む1つの図を作成したい場合があります。 + +、まず2つのプロットを作成する: + +最初のグラフは、染色体ごとにユニークな遺伝子の数を数えている。 +、まず`chromosome_name`のレベルを並べ替え、 +、染色体ごとにユニークな遺伝子をフィルタリングする必要がある。 また、読みやすくするために、Y軸のスケールを +log10スケールに変更した。 + +```{r sub1, purl=TRUE} +rna$chromosome_name <- factor(rna$chromosome_name, + levels = c(1:19,"X","Y")) + +count_gene_chromosome <- rna %>% select(chromosome_name, gene) %>% + distinct() %>% ggplot() + + geom_bar(aes(x = chromosome_name), fill = "seagreen", + position = "dodge", stat = "count") + + labs(y = "log10(n genes)", x = "chromosome") + + scale_y_log10() + +count_gene_chromosome +``` + +以下では、 +`legend.position` を `"none"` に設定することで、凡例を完全に削除することもできる。 + +```{r sub2, purl=TRUE} +exp_boxplot_sex <- ggplot(rna, aes(y=expression_log, x = as.factor(time), + color=sex)) + + geom_boxplot(alpha = 0) + + labs(y = "Mean gene exp", + x = "time") + theme(legend.position = "none") + +exp_boxplot_sex +``` + +patchwork\*\*](https://github.com/thomasp85/patchwork)パッケージ +は、`+` を使って図形を組み合わせるエレガントなアプローチを提供し、 +図形を(通常は横に並べて)並べます。 より具体的には、`|` +は明示的に横に並べ、`/`は +上に重ねる。 + +```{r install-patchwork, message=FALSE, eval=FALSE, purl=TRUE} +install.packages("patchwork") +``` + +```{r patchworkplot1, purl=TRUE} +library("patchwork") +count_gene_chromosome + exp_boxplot_sex +## or count_gene_chromosome | exp_boxplot_sex +``` + +```{r patchwork2, purl=TRUE} +count_gene_chromosome / exp_boxplot_sex +``` + +`plot_layout` と組み合わせることで、最終的なコンポジションのレイアウトをさらにコントロールし、より複雑なレイアウトを作成することができる: + +```{r patchwork3, purl=TRUE} +count_gene_chromosome + exp_boxplot_sex + plot_layout(ncol = 1) +``` + +```{r patchwork4, purl=TRUE} +count_gene_chromosome + + (count_gene_chromosome + exp_boxplot_sex) + + exp_boxplot_sex + + plot_layout(ncol = 1) +``` + +最後のプロットは `|` と `/` のコンポーザーを使っても作成できる: + +```{r patchwork5, purl=TRUE} +count_gene_chromosome / + (count_gene_chromosome | exp_boxplot_sex) / + exp_boxplot_sex +``` + +パッチワークの詳細については、 +[ウェブページ](https://patchwork.data-imaginist.com/)、またはこちらの +[ビデオ](https://www.youtube.com/watch?v=0m4yywqNPVY)をご覧ください。 + +もう一つのオプションは \*\*gridExtra`** パッケージで、 +の別々の ggplot を `grid.arrange()\` を使って一つの図にまとめることができます: + +```{r install-gridextra, message=FALSE, eval=FALSE, purl=TRUE} +install.packages("gridExtra") +``` + +```{r gridarrange-example, message=FALSE, fig.width=10, purl=TRUE} +library("gridExtra") +grid.arrange(count_gene_chromosome, exp_boxplot_sex, ncol = 2) +``` + +引数 `ncol` と `nrow` は単純な +の配置を作るのに使われるが、それに加えて、より複雑な +のレイアウトを作る ためのツールもある。 + +## プロットのエクスポート + +プロットを作成したら、お好きな +形式でファイルに保存できます。 RStudioの**Plot**ペインのExportタブでは、 +のプロットが低解像度で保存されます。これは多くのジャーナルでは受け入れられませんし、 +ではポスター用にうまく拡大縮小できません。 + +代わりに `ggsave()` 関数を使います。この関数を使うと、 +の適切な引数(`width`, `height`, `dpi`)を調整することで、プロットの +次元と解像度を簡単に変更することができます。 + +作業ディレクトリに `fig_output/` フォルダがあることを確認してください。 + +```{r ggsave-example, eval=FALSE, purl=TRUE} +my_plot <- ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + labs(title = "Mean gene expression by duration of the infection", + x = "Duration of the infection (in days)", + y = "Mean gene expression") + + guides(color=guide_legend(title="Gender")) + + theme_bw() + + theme(axis.text.x = element_text(colour = "royalblue4", size = 12), + axis.text.y = element_text(colour = "royalblue4", size = 12), + text = element_text(size = 16), + panel.grid = element_line(colour="lightsteelblue1"), + legend.position = "top") +ggsave("fig_output/mean_exp_by_time_sex.png", my_plot, width = 15, + height = 10) + +# This also works for grid.arrange() plots +combo_plot <- grid.arrange(count_gene_chromosome, exp_boxplot_sex, + ncol = 2, widths = c(4, 6)) +ggsave("fig_output/combo_plot_chromosome_sex.png", combo_plot, + width = 10, dpi = 300) +``` + +注意: パラメータ `width` と `height` は、保存されたプロットのフォントサイズ +も決定します。 + +```{r final-challenge, eval=FALSE, purl=TRUE, echo=FALSE} +### プロットの最終課題: + +## +## の練習で生成されたプロットを改良するか、あなた自身の美しいグラフを作成し てください。RStudio +## ggplot2 チートシートを参考にしてください: +## https://raw.githubusercontent.com/rstudio/cheatsheets/main/data-visualization.pdf +``` + +## その他のビジュアライゼーション用パッケージ + +ggplot2\`は非常に強力なパッケージで、我々の_tidy +data_と_tidy tools_パイプラインにうまくフィットする。 Rには他にも無視できない可視化パッケージ +がある。 + +### ベースグラフィック + +Rに付属するデフォルトのグラフィックス・システムは、しばしば_ベースR +グラフィックス_と呼ばれ、シンプルで高速である。 これは_画家またはキャンバスの +モデル_に基づいており、異なる出力がそれぞれ +互いに直接重ね合わされる(図@ref(fig:paintermodel)を参照)。 これは`ggplot2`(および後述する`lattice`)との基本的な +の違いである。 +は専用のオブジェクトを返し、それは画面上またはファイル上にレンダリングされ、 +は更新することさえできる。 + +```{r paintermodel, fig.width=12, fig.height=4, fig.cap="Successive layers added on top of each other."} +par(mfrow = c(1, 3)) +plot(1:20, main = "First layer, produced with plot(1:20)") + +plot(1:20, main = "A horizontal red line, added with abline(h = 10)") +abline(h = 10, col = "red") + +plot(1:20, main = "A rectangle, added with rect(5, 5, 15, 15)") +abline(h = 10, col = "red") +rect(5, 5, 15, 15, lwd = 3) +``` + +もうひとつの主な違いは、ベース・グラフィックスのプロット関数は、入力タイプに基づいて、 +、_正しい_ことをしようとする。 これは、 +データフレームしか入力として受け付けない`ggplot2`で、プロットをビットごとに構築する必要があるのとは、 +異なる。 + +```{r plotmethod, fig.width=8, fig.height=8, fig.cap="Plotting boxplots (top) and histograms (bottom) vectors (left) or a matrices (right)."} +par(mfrow = c(2, 2)) +boxplot(rnorm(100), + main = "rnorm(100) の Boxplot") +boxplot(matrix(rnorm(100), ncol = 10), + main = "matrix(rnorm(100), ncol = 10) の Boxplot") +hist(rnorm(100)) +hist(matrix(rnorm(100), ncol = 10)) +``` + +、`plot`、`hist`、 `boxplot`、...のような1行のコードと1つの関数で非常に素早く作成できる。 +しかし、デフォルトは必ずしも最も魅力的なものではありません。 +、図形のチューニングは、特に複雑になると(例えばファセットを生成するために +)、時間がかかり面倒になります。 + +### 格子パッケージ + +lattice`** パッケージは `ggplot2` と似ているが、 +データフレームを入力として使い、グラフィカルオブジェクトを返し、ファセットをサポートする。 +しかし、`lattice\`はグラフィックの文法に基づいておらず、 +より複雑なインターフェイスを持っている。 + +lattice\`パッケージの良いリファレンスは@latticebookだ。 + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Rによる可視化 + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/ja/episodes/60-next-steps.Rmd b/locale/ja/episodes/60-next-steps.Rmd new file mode 100644 index 000000000..da0ea2fa8 --- /dev/null +++ b/locale/ja/episodes/60-next-steps.Rmd @@ -0,0 +1,458 @@ +--- +source: Rmd +title: 次のステップ +teaching: 45 +exercises: 45 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Bioconductorプロジェクトを紹介してみましょう。 +- データコンテナの概念を紹介してみましょう。 +- オミックス解析で多用される `SummarizedExperiment` の概要を説明する。 + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- `SummarizedExperiment` とは何でしょうか? +- Bioconductor と何でしょうか? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## 次のステップ + +```{r, echo=FALSE, message=FALSE} +library("tidyverse") +``` + +バイオインフォマティクスのデータはしばしば複雑です。 これに対処するため、 +開発者は、扱う必要のあるデータのプロパティに +マッチする、特別なデータコンテナ(クラスと呼ばれる)を定義する。 + +この側面は、パッケージ間で同じ**コア・データ・インフラ**を使用する**バイオコンダクター**\[^バイオコンダクター]プロジェクト +。 この +、Bioconductorの成功に貢献したことは間違いない。 Bioconductor パッケージ +開発者は、 +プロジェクト全体に一貫性、相互運用性、安定性を提供するために、既存のインフラストラクチャを利用することをお勧めします +。 + +[^Bioconductor]: Bioconductor](https://www.bioconductor.org)は、 + 、 + R言語の生みの親の一人であるロバート・ジェントルマンによって始められた。 Bioconductorは、オミックスデータ + 分析に特化したツールを提供している。 Bioconductorは統計プログラミング言語R( + )を使用しており、オープンソース、オープン開発である。 + +このようなオミックス・データ・コンテナを説明するために、 +`SummarizedExperiment`クラスを紹介する。 + +## 実験概要 + +下図は、SummarizedExperimentクラスの構造を表しています。 + +```{r SE, echo=FALSE, out.width="80%"} +knitr::include_graphics("https://uclouvain-cbio.github.io/WSBIM1322/figs/SE.svg") +``` + +SummarizedExperimentクラスのオブジェクトには、: + +- \*\*定量的オミックスデータ + (発現データ)を含む1つ(または複数)のアッセイ \*\*、マトリックス状のオブジェクトとして格納されている。 特徴(遺伝子、 + 転写物、タンパク質、...) は行に沿って定義され、 + は列に沿って定義される。 + +- データフレームとして格納された、サンプルの共変量を含む **sample metadata** スロット。 この表の行はサンプルを表す(行は発現データの + 列と正確に一致する)。 + +- データフレームとして格納される、特徴共変量を含む **特徴メタデータ** スロット。 このデータフレームの行は、 + 式データの行と完全に一致する。 + +SummarizedExperiment\`の調整された性質は、データ操作中に +、異なるスロットの次元が +、常に一致することを保証する(すなわち、発現データの列と +サンプルメタデータの行、および発現データと +特徴メタデータの行)。 例えば、 +、アッセイから1つのサンプルを除外しなければならない場合、同じ操作でサンプルメタデータから +、自動的に除外される。 + +メタデータ・スロットは、他の構造に影響を与えることなく、 +(カラム)の共変数を追加で増やすことができる。 + +### SummarizedExperimentの作成 + +SummarizedExperiment\`を作成するために、 +の各コンポーネント、すなわちカウントマトリックス、サンプル、遺伝子 +のメタデータをcsvファイルから作成する。 これらは通常、RNA-Seqデータが +(生データが処理された後)提供される方法である。 + +```{r, echo=FALSE, message=FALSE} +rna <- read_csv("data/rnaseq.csv") + +## count matrix +counts <- rna %>% + select(gene, sample, expression) %>% + pivot_wider(names_from = sample, + values_from = expression) + +## convert to matrix and set row names +count_matrix <- counts %>% select(-gene) %>% as.matrix() +rownames(count_matrix) <- counts$gene + +## sample annotation +sample_metadata <- rna %>% + select(sample, organism, age, sex, infection, strain, time, tissue, mouse) + +## remove redundancy +sample_metadata <- unique(sample_metadata) + +## gene annotation +gene_metadata <- rna %>% + select(gene, ENTREZID, product, ensembl_gene_id, external_synonym, + chromosome_name, gene_biotype, phenotype_description, + hsapiens_homolog_associated_gene_name) + +# remove redundancy +gene_metadata <- unique(gene_metadata) + +## write to csv +write.csv(count_matrix, file = "data/count_matrix.csv") +write.csv(gene_metadata, file = "data/gene_metadata.csv", row.names = FALSE) +write.csv(sample_metadata, file = "data/sample_metadata.csv", row.names = FALSE) +``` + +- **An expression matrix**: カウント行列をロードし、 + 最初の列が行/遺伝子名を含むことを指定し、 + `data.frame` を `matrix` に変換する。 ダウンロードは + [こちら](https://carpentries-incubator.github.io/bioc-intro/data/count_matrix.csv)。 + +```{r} +count_matrix <- read.csv("data/count_matrix.csv", + row.names = 1) %>% + as.matrix() + +count_matrix[1:5, ] +dim(count_matrix) +``` + +- **サンプルを説明する表**、 + [こちら](https://carpentries-incubator.github.io/bioc-intro/data/sample_metadata.csv)。 + +```{r} +sample_metadata <- read.csv("data/sample_metadata.csv") +sample_metadata +dim(sample_metadata) +``` + +- **遺伝子を説明する表**、 + [こちら](https://carpentries-incubator.github.io/bioc-intro/data/gene_metadata.csv)。 + +```{r} +gene_metadata <- read.csv("data/gene_metadata.csv") +gene_metadata[1:10, 1:4] +dim(gene_metadata) +``` + +これらのテーブルから `SummarizedExperiment` を作成する: + +- として使用されるカウント行列。 + +- サンプルを記述したテーブルは、**サンプル + メタデータ**スロットとして使用される。 + +- 遺伝子を記述したテーブルは、**features + メタデータ**スロットとして使用される。 + +これを行うには、 +`SummarizedExperiment` コンストラクタを使って、異なるパーツをまとめることができる: + +```{r, message=FALSE, warning=FALSE} +## BiocManager::install("SummarizedExperiment") +library("SummarizedExperiment") +``` + +まず、 +カウントマトリックスとサンプルアノテーションにおいて、サンプルの順番が同じであることを確認する。また、 +カウントマトリックスと遺伝子アノテーションにおいて、遺伝子の順番が同じであることを確認する。 + +```{r} +stopifnot(rownames(count_matrix) == gene_metadata$gene) +stopifnot(colnames(count_matrix) == sample_metadata$sample) +``` + +```{r} +se <- SummarizedExperiment(assays = list(counts = count_matrix), + colData = sample_metadata, + rowData = gene_metadata) +se +``` + +### データの保存 + +以前のエピソードで行ったように、データをスプレッドシートにエクスポートするには、 +、第1章 +(小数点以下の区切り文字に`,`と`.`を使った場合の不整合の可能性、 +変数型の定義の欠如)で説明したようないくつかの制限がある。 さらに、 +スプレッドシートへのデータエクスポートは、データフレーム +や行列のような長方形のデータにのみ関係する。 + +データを保存するより一般的な方法は、Rに特有であり、 +どのオペレーティングシステムでも動作することが保証されている `saveRDS` +関数を使用することである。 このようにオブジェクトを保存すると、ディスク上にバイナリ +表現が生成されます(ここでは `rds` ファイル拡張子を使用します)。 +`readRDS` 関数を使用して R にロードし直すことができます。 + +```{r, eval=FALSE} +saveRDS(se, file = "data_output/se.rds") +rm(se) +se <- readRDS("data_output/se.rds") +head(se) +``` + +結論として、Rからデータを保存し、 +Rで再度ロードする場合、`saveRDS`と`readRDS`で保存とロードを行うのが +。 表形式のデータを、Rを使用していない誰か( +)と共有する必要がある場合は、テキストベースのスプレッドシートにエクスポートするのが、 +良い選択肢である。 + +このデータ構造を使って、 +`assay`関数で発現行列にアクセスすることができる: + +```{r} +head(assay(se)) +dim(assay(se)) +``` + +colData\`関数を使ってサンプルのメタデータにアクセスすることができる: + +```{r} +colData(se) +dim(colData(se)) +``` + +また、`rowData`関数を使ってフィーチャーのメタデータにアクセスすることもできる: + +```{r} +head(rowData(se)) +dim(rowData(se)) +``` + +### SummarizedExperimentをサブセットする + +SummarizedExperiment は、データフレームと同じように、 +数値または論理の文字でサブセットできる。 + +以下では、 +、3つの最初のサンプルの5つの最初の特徴のみを含む、SummarizedExperimentクラスの新しいインスタンスを作成します。 + +```{r} +se1 <- se[1:5, 1:3] +se1 +``` + +```{r} +colData(se1) +rowData(se1) +``` + +また、`colData()` 関数を使用して、 +サンプルメタデータから何かをサブセットしたり、`rowData()` 関数を使用して、 +フィーチャーメタデータから何かをサブセットすることもできます。 例えば、ここではmiRNAと +に感染していないサンプルだけを残している: + +```{r} +se1 <- se[rowData(se)$gene_biotype == "miRNA", + colData(se)$infection == "NonInfected"] +se1 +assay(se1) +colData(se1) +rowData(se1) +``` + + + + + + + + + + + + + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ + +時刻0と時刻8のサンプル +、最初の3遺伝子の遺伝子発現レベルを抽出する。 + +::::::::::::::: solution + +## ソリューション + +```{r, purl=FALSE} +assay(se)[1:3, colData(se)$time != 4] + +# Equivalent to +assay(se)[1:3, colData(se)$time == 0 | colData(se)$time == 8] +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## チャレンジ + +長い`rna`テーブルを使用して同じ値が得られることを確認する。 + +::::::::::::::: solution + +## ソリューション + +```{r, purl=FALSE} +rna |> + filter(gene %in% c("Asl", "Apod", "Cyd2d22"))|> + filter(time != 4) |> select(expression) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +長いテーブルと`SummarizedExperiment`は同じ +情報を含むが、単に構造が異なるだけである。 各アプローチにはそれぞれ +独自の利点がある。前者は `tidyverse` パッケージに適しており、 +一方、後者は多くのバイオインフォマティクスと +統計処理ステップに適した構造である。 例えば、 +`DESeq2`パッケージを使用した典型的なRNA-Seq分析である。 + +#### メタデータに変数を追加する + +メタデータに情報を追加することもできる。 +サンプルが採取されたセンターを追加したいとします... + +```{r} +colData(se)$center <- rep("University of Illinois", nrow(colData(se))) +colData(se) +``` + +これは、メタデータ・スロットが、 +、他の構造に影響を与えることなく、無限に成長できることを示している! + +### tidySummarizedExperiment + +`SummarizedExperiment` オブジェクトを操作するために tidyverse コマンドを使うことはできるのだろうか? +`tidySummarizedExperiment` パッケージを使えば可能です。 + +SummarizedExperimentオブジェクトがどのようなものか思い出してください: + +```{r, message=FALSE} +シー +``` + +tidySummarizedExperiment\`をロードし、seオブジェクト +。 + +```{r, message=FALSE} +#BiocManager::install("tidySummarizedExperiment") +library("tidySummarizedExperiment") + +se +``` + +これはまだ`SummarizedExperiment`オブジェクトなので、効率的な +構造を維持しているが、これでティブルとして見ることができる。 +の最初の行に注目してほしい。出力にはこう書いてあるが、これは `SummarizedExperiment`-`tibble` +の抽象化である。 また、出力の2行目には、 +のトランスクリプトとサンプルの数を見ることができる。 + +標準の`SummarizedExperiment`ビューに戻したい場合は、 +。 + +```{r} +options("restore_SummarizedExperiment_show" = TRUE) +se +``` + +しかし、ここではティブル・ビューを使う。 + +```{r} +options("restore_SummarizedExperiment_show" = FALSE) +se +``` + +`SummarizedExperiment` オブジェクトと対話するために、tidyverse コマンドを使用できるようになりました。 + +filter\`を使用すると、条件を使って行をフィルタリングすることができる。例えば、 +、あるサンプルのすべての行を表示することができる。 + +```{r} +se %>% filter(.sample == "GSM2545336") +``` + +select\`を使って表示したいカラムを指定することができる。 + +```{r} +se %>% select(.sample) +``` + +mutate\`を使ってメタデータ情報を追加することができる。 + +```{r} +se %>% mutate(center = "ハイデルベルク大学") +``` + +tidyverseパイプ `%>%` を使ってコマンドを組み合わせることもできます。 +の例では、`group_by` と `summarise` を組み合わせて、各サンプルの +カウントの合計を得ることができる。 + +```{r} +se %>% + group_by(.sample) %>% + summarise(total_counts=sum(counts)) +``` + +整頓されたSummarizedExperimentオブジェクトを、プロット用の通常のtibble +として扱うことができる。 + +ここでは、サンプルごとのカウント数分布をプロットしている。 + +```{r tidySE-plot} +se %>% + ggplot(aes(counts + 1, group=.sample, color=infection))+ + geom_density() + + scale_x_log10() + + theme_bw() +``` + +tidySummarizedExperimentの詳細については、パッケージ +ウェブサイト +[こちら](https://stemangiola.github.io/tidySummarizedExperiment/)を参照してください。 + +\*\*テイクホーム・メッセージ + +- SummarizedExperiment\`は、オミックスデータを効率的に保存し、 + 。 + +- これらは多くのBioconductorパッケージで使用されている。 + +RNAシーケンス解析に焦点を当てた次のトレーニング、 +、Bioconductor `DESeq2`パッケージを使って、 +差分発現解析を行う方法を学ぶ。 DESeq2`パッケージの全解析は`SummarizedExperiment\` で処理される。 + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Bioconductorは、ハイスループットな生物学データの理解( + )のためのサポートとパッケージを提供するプロジェクトである。 +- SummarizedExperiment\`は、ハイスループットのオミックスデータを保存し、 + 管理するのに便利なオブジェクトの一種である。 + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/ja/index.md b/locale/ja/index.md new file mode 100644 index 000000000..f6e3116fd --- /dev/null +++ b/locale/ja/index.md @@ -0,0 +1,18 @@ +--- +permalink: index.html +site: sandpaper::sandpaper_site +--- + +## About this course + +:::::::::::::::::::::::::::::::::::::::::: prereq + +## Prerequisites + +- Familiarity with tabular data and spreadsheets. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + + + + diff --git a/locale/ja/instructors/instructor-notes.md b/locale/ja/instructors/instructor-notes.md new file mode 100644 index 000000000..8012e4da9 --- /dev/null +++ b/locale/ja/instructors/instructor-notes.md @@ -0,0 +1,9 @@ +--- +title: 講師メモ +--- + +FIXME + + + + diff --git a/locale/ja/learners/discuss.md b/locale/ja/learners/discuss.md new file mode 100644 index 000000000..515e3baf1 --- /dev/null +++ b/locale/ja/learners/discuss.md @@ -0,0 +1,9 @@ +--- +title: Discussion +--- + +FIXME + + + + diff --git a/locale/ja/learners/reference.md b/locale/ja/learners/reference.md new file mode 100644 index 000000000..3466d35cf --- /dev/null +++ b/locale/ja/learners/reference.md @@ -0,0 +1,11 @@ +--- +{} +--- + +## Glossary + +FIXME + + + + diff --git a/locale/ja/learners/setup.md b/locale/ja/learners/setup.md new file mode 100644 index 000000000..d8805424b --- /dev/null +++ b/locale/ja/learners/setup.md @@ -0,0 +1,156 @@ +--- +title: セットアップ +--- + +- LibreOffice、Microsoft Excel、Google Sheetsなど、表計算エディターが手元にあることを確認してください。 + +- R、RStudio、パッケージをインストールしてください(下記参照)。 + +### RとRStudio + +- RとRStudioは別々にダウンロード、インストールする。 R is the + underlying statistical computing environment, but using R alone is + no fun. RStudio is a graphical integrated development environment + (IDE) that makes using R much easier and more interactive. RStudioをインストールする前に、Rをインストールしてください。 両方の + プログラムをインストールした後、 + RStudio 内にいくつかの特定の R パッケージをインストールする必要があります。 Follow the instructions below for your operating system, + and then follow the instructions to install packages. + +### You are running Windows + +
+ +::::::::::::::: solution + +## すでにRとRStudioがインストールされている場合 + +- Open RStudio, and click on "Help" > "Check for updates". If a new version is + available, quit RStudio, and download the latest version for RStudio. + +- To check which version of R you are using, start RStudio and the first thing + that appears in the console indicates the version of R you are + running. Alternatively, you can type `sessionInfo()`, which will also display + which version of R you are running. Go on + the [CRAN website](https://cran.r-project.org/bin/windows/base/) and check + whether a more recent version is available. If so, please download and install + it. You can [check here](https://cran.r-project.org/bin/windows/base/rw-FAQ.html#How-do-I-UNinstall-R_003f) for + more information on how to remove old versions from your system if you wish to do so. + +- Follow the steps in the instructions [for everyone](#for-everyone) at the + bottom of this page. + +::::::::::::::::::::::::: + +::::::::::::::: solution + +## If you don't have R and RStudio installed + +- Download R from + the [CRAN website](https://cran.r-project.org/bin/windows/base/release.htm). + +- Run the `.exe` file that was just downloaded + +- Go to the [RStudio download page](https://www.rstudio.com/products/rstudio/download/#download) + +- Under _All Installers_ select **RStudio xxxx.yy.zz-uuu.exe - Windows 10/11** (where x, y, z, and u represent version numbers) + +- ファイルをダブルクリックしてインストールする + +- Once it's installed, open RStudio to make sure it works and you don't get any + error messages + +- Follow the steps in the instructions [for everyone](#for-everyone) at the + bottom of this page. + +::::::::::::::::::::::::: + +### You are running macOS + +
+ +::::::::::::::: solution + +## すでにRとRStudioがインストールされている場合 + +- Open RStudio, and click on "Help" > "Check for updates". If a new version is + available, quit RStudio, and download the latest version for RStudio. + +- To check the version of R you are using, start RStudio and the first thing + that appears on the terminal indicates the version of R you are running. Alternatively, you can type `sessionInfo()`, which will + also display which version of R you are running. Go on + the [CRAN website](https://cran.r-project.org/bin/macosx/) and check + whether a more recent version is available. If so, please download and install + it. + +- Follow the steps in the instructions [for everyone](#for-everyone) at the + bottom of this page. + +::::::::::::::::::::::::: + +::::::::::::::: solution + +## If you don't have R and RStudio installed + +- Download R from + the [CRAN website](https://cran.r-project.org/bin/macosx/). + +- Select the `.pkg` file for the latest R version + +- Double click on the downloaded file to install R + +- It is also a good idea to install [XQuartz](https://www.xquartz.org/) (needed + by some packages) + +- Go to the [RStudio download page](https://www.rstudio.com/products/rstudio/download/#download) + +- Under _All Installers_ select **RStudio xxxx.yy.zz-uuu.dmg - macOS 10.15+** (where x, y, z, and u represent version numbers) + +- Double click the file to install RStudio + +- Once it's installed, open RStudio to make sure it works and you don't get any + error messages. + +- Follow the steps in the instructions [for everyone](#for-everyone) at the + bottom of this page. + +::::::::::::::::::::::::: + +### You are running Linux + +
+ +::::::::::::::: solution + +## Install R using your package manager and RStudio + +- Follow the instructions for your distribution + from [CRAN](https://cloud.r-project.org/bin/linux), they provide information + to get the most recent version of R for common distributions. For most + distributions, you could use your package manager (e.g., for Debian/Ubuntu run + `sudo apt-get install r-base`, and for Fedora `sudo yum install R`), but we + don't recommend this approach as the versions provided by this are + usually out of date. In any case, make sure you have at least R 4.2.0. +- Go to the RStudio download + page +- Under _All Installers_ select the version that matches your distribution, and + install it with your preferred method (e.g., with Debian/Ubuntu `sudo dpkg -i rstudio-xxxx.yy.zz-uuu-amd64.deb` at the terminal). +- Once it's installed, open RStudio to make sure it works and you don't get any + error messages. +- Follow the steps in the [instructions for everyone](#for-everyone) + +::::::::::::::::::::::::: + +### For everyone + +After installing R and RStudio, you need to install a couple of +packages that will be used during the workshop. We will also learn +about package installation during the course to explain the following +commands. For now, simply follow the instructions below: + +- Start RStudio by double-clicking the icon and then type: + +```r +install.packages(c("BiocManager", "remotes")) +BiocManager::install(c("tidyverse", "SummarizedExperiment", "hexbin", + "patchwork", "gridExtra", "lubridate")) +``` diff --git a/locale/ja/profiles/learner-profiles.md b/locale/ja/profiles/learner-profiles.md new file mode 100644 index 000000000..75b2c5cad --- /dev/null +++ b/locale/ja/profiles/learner-profiles.md @@ -0,0 +1,5 @@ +--- +title: FIXME +--- + +This is a placeholder file. Please add content here. diff --git a/locale/pt/CODE_OF_CONDUCT.md b/locale/pt/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..a820b8df5 --- /dev/null +++ b/locale/pt/CODE_OF_CONDUCT.md @@ -0,0 +1,12 @@ +--- +title: Contributor Code of Conduct +--- + +As contributors and maintainers of this project, +we pledge to follow the [The Carpentries Code of Conduct][coc]. + +Instances of abusive, harassing, or otherwise unacceptable behavior +may be reported by following our [reporting guidelines][coc-reporting]. + +[coc-reporting]: https://docs.carpentries.org/topic_folders/policies/incident-reporting.html +[coc]: https://docs.carpentries.org/topic_folders/policies/code-of-conduct.html diff --git a/locale/pt/CONTRIBUTING.md b/locale/pt/CONTRIBUTING.md new file mode 100644 index 000000000..5dfea562d --- /dev/null +++ b/locale/pt/CONTRIBUTING.md @@ -0,0 +1,151 @@ +# Contributing + +[Software Carpentry][swc-site] and [Data Carpentry][dc-site] are open source projects, +and we welcome contributions of all kinds: +new lessons, +fixes to existing material, +bug reports, +and reviews of proposed changes are all welcome. + +## Contributor Agreement + +By contributing, +you agree that we may redistribute your work under [our license](LICENSE.md). +In exchange, +we will address your issues and/or assess your change proposal as promptly as we can, +and help you become a member of our community. +Everyone involved in [Software Carpentry][swc-site] and [Data Carpentry][dc-site] +agrees to abide by our [code of conduct](CONDUCT.md). + +## How to Contribute + +The easiest way to get started is to file an issue +to tell us about a spelling mistake, +some awkward wording, +or a factual error. +This is a good way to introduce yourself +and to meet some of our community members. + +1. If you do not have a [GitHub][github] account, + you can [send us comments by email][contact]. + However, + we will be able to respond more quickly if you use one of the other methods described below. + +2. If you have a [GitHub][github] account, + or are willing to [create one][github-join], + but do not know how to use Git, + you can report problems or suggest improvements by [creating an issue][issues]. + This allows us to assign the item to someone + and to respond to it in a threaded discussion. + +3. If you are comfortable with Git, + and would like to add or change material, + you can submit a pull request (PR). + Instructions for doing this are [included below](#using-github). + +## Where to Contribute + +1. If you wish to change this lesson, + please work in , + which can be viewed at . + +2. If you wish to change the example lesson, + please work in , + which documents the format of our lessons + and can be viewed at . + +3. If you wish to change the template used for workshop websites, + please work in . + The home page of that repository explains how to set up workshop websites, + while the extra pages in + provide more background on our design choices. + +4. If you wish to change CSS style files, tools, + or HTML boilerplate for lessons or workshops stored in `_includes` or `_layouts`, + please work in . + +## What to Contribute + +There are many ways to contribute, +from writing new exercises and improving existing ones +to updating or filling in the documentation +and submitting [bug reports][issues] +about things that don't work, aren't clear, or are missing. +If you are looking for ideas, +please see [the list of issues for this repository][issues], +or the issues for [Data Carpentry][dc-issues] +and [Software Carpentry][swc-issues] projects. + +Comments on issues and reviews of pull requests are just as welcome: +we are smarter together than we are on our own. +Reviews from novices and newcomers are particularly valuable: +it's easy for people who have been using these lessons for a while +to forget how impenetrable some of this material can be, +so fresh eyes are always welcome. + +## What _Not_ to Contribute + +Our lessons already contain more material than we can cover in a typical workshop, +so we are usually _not_ looking for more concepts or tools to add to them. +As a rule, +if you want to introduce a new idea, +you must (a) estimate how long it will take to teach +and (b) explain what you would take out to make room for it. +The first encourages contributors to be honest about requirements; +the second, to think hard about priorities. + +We are also not looking for exercises or other material that only run on one platform. +Our workshops typically contain a mixture of Windows, macOS, and Linux users; +in order to be usable, +our lessons must run equally well on all three. + +## Using GitHub + +If you choose to contribute via GitHub, +you may want to look at +[How to Contribute to an Open Source Project on GitHub][how-contribute]. +In brief: + +1. The published copy of the lesson is in the `gh-pages` branch of the repository + (so that GitHub will regenerate it automatically). + Please create all branches from that, + and merge the [master repository][repo]'s `gh-pages` branch into your `gh-pages` branch + before starting work. + Please do _not_ work directly in your `gh-pages` branch, + since that will make it difficult for you to work on other contributions. + +2. We use [GitHub flow][github-flow] to manage changes: + 1. Create a new branch in your desktop copy of this repository for each significant change. + 2. Commit the change in that branch. + 3. Push that branch to your fork of this repository on GitHub. + 4. Submit a pull request from that branch to the [master repository][repo]. + 5. If you receive feedback, + make changes on your desktop and push to your branch on GitHub: + the pull request will update automatically. + +Each lesson has two maintainers who review issues and pull requests +or encourage others to do so. +The maintainers are community volunteers, +and have final say over what gets merged into the lesson. + +## Other Resources + +General discussion of [Software Carpentry][swc-site] and [Data Carpentry][dc-site] +happens on the [discussion mailing list][discuss-list], +which everyone is welcome to join. +You can also [reach us by email][contact]. + +[contact]: mailto:admin@software-carpentry.org +[dc-issues]: https://github.com/issues?q=user%3Adatacarpentry +[dc-lessons]: http://datacarpentry.org/lessons/ +[dc-site]: http://datacarpentry.org/ +[discuss-list]: http://lists.software-carpentry.org/listinfo/discuss +[github]: http://github.com +[github-flow]: https://guides.github.com/introduction/flow/ +[github-join]: https://github.com/join +[how-contribute]: https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github +[issues]: https://github.com/swcarpentry/shell-novice/issues/ +[repo]: https://github.com/swcarpentry/shell-novice/ +[swc-issues]: https://github.com/issues?q=user%3Aswcarpentry +[swc-lessons]: http://software-carpentry.org/lessons/ +[swc-site]: http://software-carpentry.org/ diff --git a/locale/pt/LICENSE.md b/locale/pt/LICENSE.md new file mode 100644 index 000000000..696cc3ae1 --- /dev/null +++ b/locale/pt/LICENSE.md @@ -0,0 +1,82 @@ +--- +title: Licenses +--- + +## Instructional Material + +All Software Carpentry, Data Carpentry, and Library Carpentry instructional material is +made available under the [Creative Commons Attribution +license][cc-by-human]. The following is a human-readable summary of +(and not a substitute for) the [full legal text of the CC BY 4.0 +license][cc-by-legal]. + +You are free: + +- to **Share**---copy and redistribute the material in any medium or format +- to **Adapt**---remix, transform, and build upon the material + +for any purpose, even commercially. + +The licensor cannot revoke these freedoms as long as you follow the +license terms. + +Under the following terms: + +- **Attribution**---You must give appropriate credit (mentioning that + your work is derived from work that is Copyright © Software + Carpentry and, where practical, linking to + http\://software-carpentry.org/), provide a [link to the + license][cc-by-human], and indicate if changes were made. You may do + so in any reasonable manner, but not in any way that suggests the + licensor endorses you or your use. + +**No additional restrictions**---You may not apply legal terms or +technological measures that legally restrict others from doing +anything the license permits. With the understanding that: + +Notices: + +- You do not have to comply with the license for elements of the + material in the public domain or where your use is permitted by an + applicable exception or limitation. +- No warranties are given. The license may not give you all of the + permissions necessary for your intended use. For example, other + rights such as publicity, privacy, or moral rights may limit how you + use the material. + +## Software + +Except where otherwise noted, the example programs and other software +provided by Software Carpentry and Data Carpentry are made available under the +[OSI][osi]-approved +[MIT license][mit-license]. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +## Trademark + +"Software Carpentry" and "Data Carpentry" and their respective logos +are registered trademarks of [Community Initiatives][ci]. + +[cc-by-human]: https://creativecommons.org/licenses/by/4.0/ +[cc-by-legal]: https://creativecommons.org/licenses/by/4.0/legalcode +[mit-license]: https://opensource.org/licenses/mit-license.html +[ci]: http://communityin.org/ +[osi]: https://opensource.org diff --git a/locale/pt/README.md b/locale/pt/README.md new file mode 100644 index 000000000..fec09d0f3 --- /dev/null +++ b/locale/pt/README.md @@ -0,0 +1,75 @@ +# Introduction to genomic data analysis with R and Bioconductor + +[![Create a Slack Account with us](https://img.shields.io/badge/Create_Slack_Account-The_Carpentries-071159.svg)](https://swc-slack-invite.herokuapp.com/) + +## Contributing + +We welcome all contributions to improve the lesson! Maintainers will +do their best to help you if you have any questions, concerns, or +experience any difficulties along the way. + +We'd like to ask you to familiarize yourself with our Contribution +Guide and have a look at the [more detailed +guidelines][lesson-example] on proper formatting, ways to render the +lesson locally, and even how to write new episodes. + +Please see the current list of [issues][FIXME] for ideas for +contributing to this repository. For making your contribution, we use +the GitHub flow, which is nicely explained in the chapter +Contributing to a +Project +in Pro Git by Scott Chacon. + +Look for the tag +![good\_first\_issue](https://img.shields.io/badge/-good%20first%20issue-gold.svg). This +indicates that the maintainers will welcome a pull request fixing this +issue. + +## Useful links + +- If you're going to be developing lesson material for the first time + according to our design principles, consider reading the + [Carpentries Curriculum Development Handbook][cdh] +- Consult the [Lesson Example][lesson-example] website to find out more about + working with the lesson template + +## Lesson team + +This lesson has been developed and is current maintained by + +- Laurent Gatto (maintainer) +- Charlotte Soneson +- Jenny Drnevich +- Robert Castelo +- Kevin Rue-Albert + +We would also like to acknowledge the contributions of: + +- Oliver Crook, Sarah Kaspar, Nick Hirschmueller, Lisa Breckels and Maria Doyle for their contributions during the Bioconductor introduction workshop in Heidelberg, as part of EuroBioc2021 |> 2022. +- Axelle Loriot, Marco Chiapelle, Manon Martin and Toby Hodges for various contributions and discussions. +- lmsimp, alorot, manonmartin, mchiapello, stavares843, JennyZadeh, csdaw, ninja-1337, fursham-h, lagerratrobe, fmichonneau, federicomarini, tobyhodges for pull requests. + +If we have contributed but we missed you, apologies, and feel free to add yourself with a PR. + +## Authors + +A list of contributors to the lesson can be found in [AUTHORS](AUTHORS) + +## Citation + +To cite this lesson, please consult with [CITATION](CITATION) + +[lesson-example]: https://carpentries.github.io/lesson-example +[cdh]: https://cdh.carpentries.org + +## Testing locally + +To test locally, run the following in the lessons directory: + +```r +sandpaper::serve() +``` + +For more details, see the [workbench installation +instructions](https://carpentries.github.io/workbench/#installation]. + diff --git a/locale/pt/config.yaml b/locale/pt/config.yaml new file mode 100644 index 000000000..204cb59c5 --- /dev/null +++ b/locale/pt/config.yaml @@ -0,0 +1,61 @@ +#------------------------------------------------------------ +#Values for this lesson. +#------------------------------------------------------------ +#Which carpentry is this (swc, dc, lc, or cp)? +#swc: Software Carpentry +#dc: Data Carpentry +#lc: Library Carpentry +#cp: Carpentries (to use for instructor training for instance) +#incubator: The Carpentries Incubator +carpentry: 'incubator' +#Overall title for pages. +title: 'Introduction to data analysis with R and Bioconductor' +#Date the lesson was created (YYYY-MM-DD, this is empty by default) +created: '2020-09-14' +#Comma-separated list of keywords for the lesson +keywords: 'software, data, lesson, The Carpentries' +#Life cycle stage of the lesson +#possible values: pre-alpha, alpha, beta, stable +life_cycle: 'stable' +#License of the lesson +license: 'CC-BY 4.0' +#Link to the source repository for this lesson +source: 'https://github.com/carpentries-incubator/bioc-intro' +#Default branch of your lesson +branch: 'main' +#Who to contact if there are any issues +contact: 'laurent.gatto@uclouvain.be' +#Navigation ------------------------------------------------ +#Use the following menu items to specify the order of +#individual pages in each dropdown section. Leave blank to +#include all pages in the folder. +#Example ------------- +#episodes: +#- introduction.md +#- first-steps.md +#learners: +#- setup.md +#instructors: +#- instructor-notes.md +#profiles: +#- one-learner.md +#- another-learner.md +#Order of episodes in your lesson +episodes: + - 10-data-organisation.Rmd + - 20-r-rstudio.Rmd + - 23-starting-with-r.Rmd + - 25-starting-with-data.Rmd + - 30-dplyr.Rmd + - 40-visualization.Rmd + - 60-next-steps.Rmd +#Information for Learners +learners: +#Information for Instructors +instructors: +#Learner Profiles +profiles: +#Customisation --------------------------------------------- +#This space below is where custom yaml items (e.g. pinning +#sandpaper and varnish versions) should live +url: 'https://carpentries-incubator.github.io/bioc-intro' diff --git a/locale/pt/episodes/10-data-organisation.Rmd b/locale/pt/episodes/10-data-organisation.Rmd new file mode 100644 index 000000000..6a7a685eb --- /dev/null +++ b/locale/pt/episodes/10-data-organisation.Rmd @@ -0,0 +1,794 @@ +--- +source: Rmd +title: Data organisation with spreadsheets +teaching: 30 +exercises: 30 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Aprenda sobre planilhas, seus pontos fortes e fracos. +- How do we format data in spreadsheets for effective data use? +- Learn about common spreadsheet errors and how to correct them. +- Organise your data according to tidy data principles. +- Learn about text-based spreadsheet formats such as the comma-separated (CSV) or tab-separated (TSV) formats. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- How to organise tabular data? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +> This episode is based on the Data Carpentries's _Data Analysis and +> Visualisation in R for Ecologists_ lesson. + +## Spreadsheet programs + +**Question** + +- What are basic principles for using spreadsheets for good data + organization? + +**Objective** + +- Describe best practices for organizing data so computers can make + the best use of datasets. + +**Keypoint** + +- Good data organization is the foundation of any research project. + +Uma boa organização dos dados é a base do seu projeto de pesquisa. A maioria dos pesquisadores tem dados ou faz entrada de dados em +formato de planilhas. Programas de análise de tabelas são interfaces +gráficas muito úteis para projetar dados e lidar com funções e controle de qualidade. Ver também @Broman:2018. + +### Spreadsheet outline + +Spreadsheets are good for data entry. Portanto, temos muitos dados +em planilhas. Muito do seu tempo como pesquisador será gasto em +desembaralhar seus dados e a forma como foram inseridos. Não é o mais divertido, mas é +necessário. Vamos te ensinar como pensar sobre organização de dados e +algumas práticas para um melhor desembaraço dos dados. + +### What this lesson will not teach you + +- How to do _statistics_ in a spreadsheet +- How to do _plotting_ in a spreadsheet +- How to _write code_ in spreadsheet programs + +If you're looking to do this, a good reference is Head First +Excel, +published by O'Reilly. + +### Why aren't we teaching data analysis in spreadsheets + +- Data analysis in spreadsheets usually requires a lot of manual + work. Se você alterar um parâmetro ou efetuar uma análise com um + novo conjunto de dados, normalmente terá de refazer tudo à mão. (Nós + sabemos que é posível criar macros, mas veja o próximo ponto) + +- It is also difficult to track or reproduce statistical or plotting + analyses done in spreadsheet programs when you want to go back to + your work or someone asks for details of your analysis. + +Muitos programas para análise de tabelas estão disponíveis. Uma vez que a maioria dos participantes +utiliza o Excel como o seu principal programa de análise de planilhas, esta lição +utilizará exemplos do Excel. Um programa de análises de planilhas gratuito, que também pode ser usado +é o LibreOffice. Os comandos podem diferir um pouco entre programas, +mas a ideia geral é a mesma. + +Programas de análise de planilhas englobam muitas das coisas que precisamos ser capazes de +fazer como pesquisadores. We can use them for: + +- Data entry +- Organizing data +- Subsetting and sorting data +- Statistics +- Plotting + +Spreadsheet programs use tables to represent and display data. Dados +formatados como tabelas é também o tema principal deste capítulo, e +veremos como organizar dados em tabelas de uma forma padronizada que +garante uma análise a jusante eficiente. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge: Discuss the following points with your neighbour + +- Have you used spreadsheets, in your research, courses, + or at home? +- What kind of operations do you do in spreadsheets? +- Which ones do you think spreadsheets are good for? +- Have you accidentally done something in a spreadsheet program that made you + frustrated or sad? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +### Problems with spreadsheets + +Spreadsheets are good for data entry, but in reality we tend to +use spreadsheet programs for much more than data entry. Usamos elas +para criar tabelas de dados para publicações, para gerar estatísticas +sumarizadas e fazer figuras. + +Gerar tabelas para publicações em uma planilha não é +ideal - frequentemente, ao formatar uma tabela de dados para publicação, Estamos +relatando estatísticas chaves resumidas de uma forma que não é realmente para +ser lida como dado, e muitas vezes envolve uma formatação especial +(mesclando células, criando margens, tornando-a bonita). Aconselhamos que +faça esse tipo de operação dentro do seu software de edição de documentos. + +As duas últimas aplicações, a geração de estatísticas e números, +deve ser usada com cuidado: por causa da natureza gráfica dos programas, arrastar e soltar, pode ser muito difícil, se não impossível, se quiser repetir seus movimentos (e para qualquer outra pessoa reproduzir), particularmente se suas estatísticas +ou números exigem que você faça cálculos mais complexos. Além disso, +ao efetuar cálculos numa planilha, é fácil aplicar acidentalmente uma +fórmula ligeiramente diferente a várias células adjacentes. Quando se utiliza um programa de estatística baseado na linha de comandos +como o R ou o SAS, é praticamente +impossível aplicar um cálculo a uma observação no seu conjunto de dados +mas não a outra, a menos que o faça de propósito. + +### Using spreadsheets for data entry and cleaning + +In this lesson, we will assume that you are most likely using Excel as +your primary spreadsheet program - there are others (gnumeric, Calc +from OpenOffice), and their functionality is similar, but Excel seems +to be the program most used by biologists and biomedical researchers. + +In this lesson we're going to talk about: + +1. Formatting data tables in spreadsheets +2. Formatting problems +3. Exporting data + +## Formatting data tables in spreadsheets + +**Questions** + +- How do we format data in spreadsheets for effective data use? + +**Objectives** + +- Describe best practices for data entry and formatting in + spreadsheets. + +- Apply best practices to arrange variables and observations in a + spreadsheet. + +**Keypoints** + +- Never modify your raw data. Sempre fazer uma cópia antes de fazer quaisquer alterações. + +- Keep track of all of the steps you take to clean your data in a + plain text file. + +- Organise your data according to tidy data principles. + +O erro mais comum cometido é tratar programas de análise de planilha como cadernos de +laboratórios, ou seja, dependendo do contexto, notas na margem, layout espacial +de dados e campos para transmitir informações. Como seres humanos, podemos +(normalmente) interpretar estas coisas, mas os computadores não vêem a informação +da mesma forma e, a menos que expliquemos ao computador o que cada +coisa significa (e isso pode ser difícil!), ele não será capaz de ver como +os dados se encaixam. + +Utilizando o poder dos computadores, podemos gerir e analisar dados de formas muito +mais eficazes e rápidas, mas para utilizar esse poder, temos de +configurar os nossos dados para que o computador os possa compreender (e +os computadores são muito literais). + +É por isso que é extremamente importante criar tabelas bem formatadas +desde o início - antes mesmo de começar a introduzir os dados da sua +primeira experiência. Uma boa organização dos dados é a base do seu projeto de pesquisa. Ela pode tornar mais fácil ou mais difícil trabalhar com +os seus dados ao longo da análise, assim vale a pena pensar nisso quando +estiver introduzindo os dados ou a preparar a experiência. Você pode +configurar as coisas de formas diferentes em planilhas, mas algumas destas +opções podem limitar sua capacidade de trabalhar com os dados de outros programas +ou limitar o você de daqui há 6 meses e o seu colaborador de trabalhar com +os dados. + +\*\*Nota: Os melhores layouts/formatos (bem como o software e as interfaces) para a introdução e análise de dados podem ser diferentes. É +importante ter isso em conta e procurar automatizar a conversão +de um para outro. + +### Keeping track of your analyses + +When you're working with spreadsheets, during data clean up or +analyses, it's very easy to end up with a spreadsheet that looks very +different from the one you started with. In order to be able to +reproduce your analyses or figure out what you did when a reviewer or +instructor asks for a different analysis, you should + +- create a new file with your cleaned or analysed data. Não modifique + o conjunto de dados original, ou você nunca saberá por onde começou! + +- keep track of the steps you took in your clean up or analysis. Você + deve acompanhar estes passos como você faria em passos de um experimento de bancada. Nós + recomendamos que você faça isso em um arquivo de texto simples armazenado na mesma pasta + do arquivo de dados. + +This might be an example of a spreadsheet setup: + +![](fig/spreadsheet-setup-updated.png) + +Put these principles in to practice today during your exercises. + +Enquanto o controle de versão está fora de escopo, você pode ver a aula +do Carpentries em +['Git'](https://swcarpentry. ithub.io/git-novice/) para aprender como +manter um **controle de versão** sobre seus dados. Veja também este blog +post para um tutorial rápido, ou +@Perez-Riverol:2016 para um exemplo mais voltado à pesquisa. + +### Structuring data in spreadsheets + +The cardinal rules of using spreadsheet programs for data: + +1. Coloque todas as suas variáveis em colunas - a coisa que você está medindo, + como 'peso' ou 'temperatura'. +2. Coloque cada observação em sua própria linha. +3. Não combina várias informações em uma só célula. Às vezes + parece apenas uma coisa, mas pense se essa é a única maneira + você vai conseguir usar ou ordenar esses dados. +4. Deixe os dados brutos, brutos - não mude! +5. Exportar os dados limpos para um formato baseado em texto, como o formato CSV + (valores separados por vírgula). Isso garante que qualquer pessoa possa usar + os dados e é exigido pela maioria dos repositórios de dados. + +Por exemplo, temos dados de pacientes que visitaram vários hospitais +em Bruxelas, Bélgica. Eles registraram a data da visita, +o hospital, o gênero, o peso e o grupo sanguíneo dos pacientes. + +If we were to keep track of the data like this: + +![](fig/multiple-info.png) + +the problem is that the ABO and Rhesus groups are in the same `Blood` +type column. Então, se eles quiserem ver todas as observações do grupo A +ou ver as distribuições de peso por grupo ABO, seria complicado +fazer isso usando essa configuração de dados. Em vez disso, se colocarmos os grupos ABO e Rhesus +em colunas diferentes, você poderá ver que isso seria muito mais fácil. + +![](fig/single-info.png) + +An important rule when setting up a datasheet, is that **columns are +used for variables** and **rows are used for observations**: + +- columns are variables +- rows are observations +- cells are individual values + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge: We're going to take a messy dataset and describe how we would clean it up. + +1. Download a messy dataset by clicking + [here](https://github.com/UCLouvain-CBIO/WSBIM1207/raw/master/data/messy_covid.xlsx). + +2. Abra os dados em um programa de planilha. + +3. Podemos ver que existem duas abas. Os dados contêm diversas + variáveis clínicas registadas em vários hospitais de Bruxelas durante + a primeira e a segunda ondas da COVID-19 em 2020. Como se pode ver, os dados de + foram registados de forma diferente durante as ondas de Março e Novembro. Agora você é a pessoa responsável por este projeto e você quer + poder começar a analisar os dados. + +4. Com a pessoa ao seu lado, identifique o que há de errado com esta planilha. Também discuta os passos que você precisa dar para limpar + as abas associadas à primeira e à segunda ondas, e para colocá-los todos juntos em uma planilha. + +**Importante:** Não se esqueça do nosso primeiro conselho: criar um +novo arquivo (ou aba) para os dados limpos, nunca modificar os dados originais +(brutos). + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +After you go through this exercise, we'll discuss as a group what was +wrong with this data and how you would fix it. + + + + + + + + + + + + + + + + + + + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge: Once you have tidied up the data, answer the following questions: + +- How many men and women took part in the study? +- How many A, AB, and B types have been tested? +- As above, but disregarding the contaminated samples? +- How many Rhesus + and - have been tested? +- How many universal donors (O-) have been tested? +- What is the average weight of AB men? +- How many samples have been tested in the different hospitals? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +An **excellent reference**, in particular with regard to R scripting +is the _Tidy Data_ paper @Wickham:2014. + +## Common spreadsheet errors + +**Questions** + +- What are some common challenges with formatting data in spreadsheets + and how can we avoid them? + +**Objectives** + +- Recognise and resolve common spreadsheet formatting problems. + +**Keypoints** + +- Avoid using multiple tables within one spreadsheet. +- Avoid spreading data across multiple tabs. +- Record zeros as zeros. +- Use an appropriate null value to record missing data. +- Don't use formatting to convey information or to make your spreadsheet look pretty. +- Place comments in a separate column. +- Record units in column headers. +- Include only one piece of information in a cell. +- Avoid spaces, numbers and special characters in column headers. +- Avoid special characters in your data. +- Record metadata in a separate plain text file. + + + + + + + + + +There are a few potential errors to be on the lookout for in your own +data as well as data from collaborators or the Internet. Se você esta +ciente dos erros e do possível efeito negativo na análise e interpretação de resultados a jusante, isso pode servir de motivação para você e para +os membros do seu projeto para tentar evitá-los. Fazendo pequenas alterações +na forma como você formata seus dados em planilhas pode ter um grande +impacto na eficiência e confiabilidade na limpeza de dados +e análise. + +- [Using multiple tables](#tables) +- [Using multiple tabs](#tabs) +- [Not filling in zeros](#zeros) +- [Using problematic null values](#null) +- [Using formatting to convey information](#formatting) +- [Using formatting to make the data sheet look pretty](#formatting_pretty) +- [Placing comments or units in cells](#units) +- [Entering more than one piece of information in a cell](#info) +- [Using problematic field names](#field_name) +- [Using special characters in data](#special) +- [Inclusion of metadata in data table](#metadata) + +### Using multiple tables {#tables} + +A common strategy is creating multiple data tables within one +spreadsheet. Isso confunde o computador, então não faça isso! Quando você +cria múltiplas tabelas dentro de uma planilha, você está desenhando falsas +associações entre as coisas para o computador, que vê cada linha como +uma observação. Você também está potencialmente usando o mesmo nome em +múltiplos lugares, o que dificultará a limpeza de seus dados em +um formulário utilizável. The example below depicts the problem: + +![](fig/2_datasheet_example.jpg) + +In the example above, the computer will see (for example) row 4 and +assume that all columns A-AF refer to the same sample. Esta linha +representa na verdade quatro amostras distintas (amostra 1 para cada uma das +datas diferentes de coleção - dia 29 de maio, 12 de junho, 19 de junho, e +26 de junho), assim como algumas estatísticas calculadas uma média (avr) +e um erro padrão (SEM) para duas dessas amostras. Outras linhas da planilha são igualmente problemáticas. + +### Using multiple tabs {#tabs} + +But what about workbook tabs? Essa parece uma maneira fácil de organizar +dados, certo? Bem, sim e não. Quando você criar abas extras, você impede que o computador veja conexões nos dados que existem (você +tem que introduzir funções específicas em uma planilha ou o script +para garantir essa conexão). Digamos, por exemplo, que faz uma +aba para cada dia de medição. + +This isn't good practice for two reasons: + +1. you are more likely to accidentally add inconsistencies to your + data if each time you take a measurement, you start recording data + in a new tab, and + +2. mesmo se você conseguir evitar que todas as inconsistências entrem, + você irá adicionar um passo extra antes de analisar os dados + pois terá que combinar esses dados em um único + dataset. Você terá que dizer explicitamente ao computador como + combinar as abas - e se as abas forem formatadas de forma inconsistente, você + talvez tenha até que combiná-las manualmente. + +Na próxima vez que você estiver inserindo dados, e pense em criar outra aba +ou tabela, Pergunte se você poderia evitar adicionar esta aba adicionando +outra coluna à sua planilha original. Usamos várias abas em +nosso exemplo de um arquivo de dados confuso, mas agora você viu como pode +reorganizar seus dados para os consolidar através de abas. + +Sua planilha pode ficar muito longa durante o experimento. Isso dificulta a entrada de dados se você não consegue ver os cabeçalhos +no topo da planilha. Mas não repita a sua linha de +cabeçalho. Ele pode facilmente se misturar com os dados, levando a problemas +ao longo da análise. Em vez disso, você pode congelar a coluna +cabeçalho +para que elas permaneçam visíveis mesmo quando você tiver uma planilha com muitas linhas. + +### Not filling in zeros {#zeros} + +It might be that when you're measuring something, it's usually a zero, +say the number of times a rabbit is observed in the survey. Porquê dar-se ao trabalho de +escrever o número zero nessa coluna, quando a maior parte serão zeros? + +No entanto, há uma diferença entre uma célula com um zero e uma célula em branco em uma planilha. Para o computador, um zero é de fato um dado. Você teve informações sobre ele e o mediu. Uma célula em branco significa que a informação não foi medida e o computador +irá interpretá-la como um valor desconhecido (também conhecido como um valor +nulo ou valor faltando). + +As planilhas ou programas estatísticos provavelmente interpretarão erradamente +células em branco que você pretende deveriam ser zeros. Ao não inserir o valor de +sua observação, você está dizendo ao seu computador para representar esses dados +como desconhecido ou faltando (nulos ou null). Isso pode causar problemas com cálculos ou análises posteriores. Por exemplo, a média de um conjunto de números +que inclui um único valor nulo é sempre nulo (porque o computador +não consegue adivinhar o valor das observações que faltam). Porque +disso é muito importante gravar zeros como zeros e os +dados ausentes como nulos. + +### Using problematic null values {#null} + +**Example**: using -999 or other numerical values (or zero) to +represent missing data. + +**Solutions**: + +There are a few reasons why null values get represented differently +within a dataset. Às vezes, valores nulos confusos são automaticamente +gravados a depender do dispositivo de medição. Se for esse o caso, não há +muito que se possa fazer, mas pode ser resolvido na limpeza de dados com uma ferramenta +como +[OpenRefine](https://www.datacarpentry.org/OpenRefine-ecology-lesson/) +antes da análise. Outras vezes valores nulos diferentes são usados para transmitir +diferentes razões porque os dados não estão lá. Essa é uma informação +importante para capturar, mas está em vigor usando uma coluna para capturar +dois tipos de informação diferentes. Assim como para [usando formatação para transmitir informação](#formatting) seria bom aqui criar uma nova coluna +como 'data\_missing' e usar essa coluna para capturar as diferentes razões para o dado ser nulo. + +Seja qual for a razão, é um problema se dados desconhecidos ou ausentes são +registrados como -999, 999 ou 0. + +Muitos programas estatísticos não reconhecerão que esses valores se destinam a +a representar valores (null) ausentes. A forma como esses valores são interpretados +dependerá do software que você usa para analisar seus dados. É +essencial usar um indicador de dados nulos claramente definido e consistente. + +Espaços em branco (maioria dos aplicativos) e NA (para R) são boas +escolhas. @White:2013 explain good choices for indicating null values +for different software applications in their article: + +![](fig/3_white_table_1.jpg) + +### Using formatting to convey information {#formatting} + +**Example**: highlighting cells, rows or columns that should be +excluded from an analysis, leaving blank rows to indicate +separations in data. + +![](fig/formatting.png) + +**Solution**: create a new field to encode which data should be +excluded. + +![](fig/good_formatting.png) + +### Using formatting to make the data sheet look pretty {#formatting\_pretty} + +**Example**: merging cells. + +**Solução**: se você não for cuidadoso, formatar uma tabela para ser mais +esteticamente agradável pode comprometer a capacidade do seu computador de identificar +associações nos dados. As células fundidas tornarão os seus dados ilegíveis +por softwares estatístico. Considere a reestruturação de seus dados de forma a +que você não precisará mesclar/combinar células para organizar seus dados. + +### Placing comments or units in cells {#units} + +Most analysis software can't see Excel or LibreOffice comments, and +would be confused by comments placed within your data cells. Como o +descrito acima para a formatação, crie outro campo se você precisar +adicionar anotações a uma linha. Da mesma forma, não inclua unidades de medida nas células: idealmente, +todas as medidas que se coloca numa coluna devem estar na mesma unidade, mas se por alguma razão não estiverem, crie outro campo e +especifique as unidades em que a célula está. + +### Entering more than one piece of information in a cell {#info} + +**Example**: Recording ABO and Rhesus groups in one cell, such as A+, +B+, A-, ... + +**Solução**: Não incluir mais do que uma informação numa célula. Isso limitará as maneiras pelas quais você pode analisar seus dados. Se +precisar destas duas medidas, crie sua tabela para incluir +estas informações. Por exemplo, inclua uma coluna para o grupo ABO e +uma para o grupo Rhesus. + +### Using problematic field names {#field\_name} + +Choose descriptive field names, but be careful not to include spaces, +numbers, or special characters of any kind. Os espaços podem ser +mal interpretados por analisadores que utilizam espaços em branco como delimitadores e alguns programas +não gostam de nomes de campos que são cadeias de texto que começam com +números. + +Os sublinhados (`_`) são uma boa alternativa aos espaços. Considere escrever +nomes de forma as palavras se separarem por letras maiúsculas (como este: ExampleFileName) para melhorar a legibilidade. Lembre-se que as abreviações que fazem sentido no momento +podem não ser tão óbvias em 6 meses, mas não exagere com nomes que +são excessivamente longos. Incluindo as unidades de medida no campo os nomes evitam +confusão e permitem que outros interpretem prontamente suas colunas. + +**Examples** + +| Good Name | Good Alternative | Avoid | +| -------------------------------------------------------------- | ---------------------------------------- | ------------------------------------ | +| Max\_temp\_C | MaxTemp | Maximum Temp (°C) | +| Precipitation\_mm | Precipitation | precmm | +| Mean\_year\_growth | MeanYearGrowth | Mean growth/year | +| sex | sex | M/F | +| weight | weight | w. | +| cell\_type | CellType | Cell Type | +| Observation\_01 | first\_observation | 1st Obs | + +### Using special characters in data {#special} + +**Example**: You treat your spreadsheet program as a word processor +when writing notes, for example copying data directly from Word or +other applications. + +**Solução**: Essa é uma estratégia comum. Por exemplo, ao escrever +mais texto em uma célula, as pessoas muitas vezes incluem quebras de linha, e-dashes, +etc. em sua planilha. Além disso, ao copiar dados de +aplicações como Word, caracteres de formatação e +não-padrão (tais como aspas alinhadas à esquerda e à direita) estão +incluídos. Ao exportar esses dados para um ambiente de codificação/estatística +ou em um banco de dados, coisas perigosas podem ocorrer, +como linhas sendo cortadas ao meio e os erros de codificação são lançados. + +As melhores práticas gerais são evitar a adição de caracteresextras como novas linhas, abas e colunas. Em outras palavras, trate uma célula de texto como se +fosse um simples formulário online que pode conter apenas texto e espaços. + +### Inclusion of metadata in data table {#metadata} + +**Example**: You add a legend at the top or bottom of your data table +explaining column meaning, units, exceptions, etc. + +**Solution**: Recording data about your data ("metadata") is +essential. Mesmo que você conheça muito bem seus dados enquanto os coleta e analisa, as chances de que você lembrará que a variável "sglmemgp" significa cada membro de um grupo, ou o exato algorítimo usado diminuem com o passar dos mêses. + +Também existem muitas razões pelas quais outras pessoas podem querer examinar ou +usar seus dados - para entender suas descobertas, para verificar suas descobertas, +para rever uma publicação submetida, para replicar seus resultados, para +projetar um estudo semelhante, ou até mesmo para arquivar seus dados para acesso e +reutiliza-los. Embora os dados sejam, por definição, +legíveis por máquinas, a compreensão do seu significado é uma tarefa para humanos. A importância de documentar os seus dados durante a fase de coleta +e análise da sua investigação não pode ser subestimada, +especialmente se a sua investigação for fazer parte do registo académico. + +No entanto, os metadados não devem estar contidos no arquivo de dados +em si. Ao contrário de uma tabela em um papel ou um arquivo suplementar metadados (em forma de legendas) não devem ser incluídos em um arquivo de dados já que esta informação +não é de dados, e incluir isso pode interromper como o computador interpreta seu arquivo de dados. Em vez disso, os metadados devem ser armazenados +como um arquivo separado, no mesmo diretório do seu arquivo de dados de preferência, +em formato de texto simples com um nome que claramente o associa ao seu arquivo de dados. Como arquivos de metadados são no formato de texto livre, eles também +permitem que você adicione comentários, unidades, informações sobre como valores nulos +são codificados, etc. Informações que são importantes na documentação, mas podem interromper a formatação +do seu arquivo de dados. + +Além disso, os metadados do arquivo ou do banco de dados descrevem como arquivos que +compõem o conjunto de dados se relacionam entre si; em que formato eles estão; e +se eles superpõe ou são substituídos por arquivos anteriores. Um arquivo readme.txt +presente na pasta é a maneira clássica de contabilizar todos os arquivos e pastas +em um projeto. + +(Texto sobre metadados adaptados do curso Pesquisa Dados +[MANTRA](https://datalib.edina.ac.uk/mantra) pela EDINA e Biblioteca de Dados, +Universidade de Edinburgh. MANTRA está licenciado sob uma Creative Commons +Atribuição 4.0 International +License.) + +## Exporting data + +**Question** + +- How can we export data from spreadsheets in a way that is useful for + downstream applications? + +**Objectives** + +- Store spreadsheet data in universal file formats. +- Export data from a spreadsheet to a CSV file. + +**Keypoints** + +- Data stored in common spreadsheet formats will often not be read + correctly into data analysis software, introducing errors into your + data. + +- Exporting data from spreadsheets to formats like CSV or TSV puts it + in a format that can be used consistently by most programs. + +Armazenando os dados com os quais você trabalhará para suas análises no formato de arquivo Excel +padrão (`*. ls` or `*.xlsx` - dependendo da versão do Excel) não é uma boa ideia. Por quê? + +- Because it is a proprietary format, and it is possible that in the + future, technology won't exist (or will become sufficiently rare) to + make it inconvenient, if not impossible, to open the file. + +- Other spreadsheet software may not be able to open files saved in a + proprietary Excel format. + +- Different versions of Excel may handle data differently, leading to + inconsistencies. [Dates](https://datacarpentry.org/spreadsheet-ecology-lesson/03-dates-as-data/index.html) + é um exemplo bem documentado de inconsistências no armazenamento de dados. + +- Finally, more journals and grant agencies are requiring you to + deposit your data in a data repository, and most of them don't + accept Excel format. Ele precisa estar em um dos formatos discutidos + abaixo. + +- The above points also apply to other formats such as open data + formats used by LibreOffice / Open Office. Estes formatos não são + estáticos e não são analisados da mesma maneira por diferentes softwares + ou pacotes. + +Armazenar dados em um formato universal, aberto e estático ajudará a lidar com este problema. Tente formatos delimitado por tabulações (valores separados por tabulação ou TSV) ou +delimitado por vírgulas (valores separados por vírgula ou CSV). Arquivos CSV são arquivos com texto +simples onde as colunas são separadas por vírgulas, portanto 'vírgula +separam valores' ou CSV (do inglês, comma separated files). A vantagem de um arquivo CSV em um +Excel/SPSS/etc. é que podemos abrir e ler um arquivo CSV usando +praticamente qualquer software, incluindo editores de texto simples como TextEdit ou +NotePad. Os dados em um arquivo CSV também podem ser facilmente importados para outros formatos +e ambientes, como SQLite e R. Nós não estamos vinculados a uma determinada versão +de um certo programa caro quando trabalhamos com arquivos CSV +então é um bom formato trabalhar com o máximo de portabilidade e resistência. A maioria dos programas de planilha pode delimitar textos +formatos como CSV facilmente, embora eles possam dar a você um aviso durante +a exportação do arquivo que o formato original será perdido. + +To save a file you have opened in Excel in CSV format: + +1. No menu superior selecione 'Arquivo' e 'Salvar como'. +2. No campo "Formato", selecione da lista "Comma Separated + Values" (`*.csv`). +3. Verifique o nome do arquivo e o local onde você quer salvar-lo e pressione 'Salvar'. + +Uma nota importante para compatibilidade retroativa: você pode abrir os arquivos CSV +em Excel! + +```{r, results="markup", fig.cap="Saving an Excel file to CSV.", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/excel-to-csv.png") +``` + +**A note on R and `xls`**: There are R packages that can read `xls` +files (as well as Google spreadsheets). É até possível acessar +diferentes abas nos documentos 'xls'. + +**But** + +- some of these only work on Windows. +- this equates to replacing a (simple but manual) export to `csv` with + additional complexity/dependencies in the data analysis R code. +- data formatting best practice still apply. +- Is there really a good reason why `csv` (or similar) is not + adequate? + +### Caveats on commas + +In some datasets, the data values themselves may include commas +(,). Nesse caso, o software que você utiliza (incluindo o Excel) irá provavelmente exibir +de forma incorreta os dados em colunas. Isso é porque +as vírgulas que fazem parte dos valores de dados serão interpretadas como +delimitadores. + +For example, our data might look like this: + +``` +species_id,genus,species,taxa +AB,Amphispiza,bilineata,Bird +AH,Ammospermophilus,harrisi,Rodent, not censused +AS,Ammodramus,savannarum,Bird +BA,Baiomys,taylori,Rodent +``` + +In the record `AH,Ammospermophilus,harrisi,Rodent, not censused` the +value for `taxa` includes a comma (`Rodent, not censused`). If we try +to read the above into Excel (or other spreadsheet program), we will +get something like this: + +```{r, results="markup", fig.cap="The risks of having commas inside comma-separated data.", echo=FALSE, purl=FALSE, out.width="80%", fig.align="center"} +knitr::include_graphics("fig/csv-mistake.png") +``` + +The value for `taxa` was split into two columns (instead of being put +in one column `D`). Isso pode propagar-se para uma série de outros +erros. Por exemplo, a coluna extra será interpretada como uma coluna +com muitos valores ausentes (e sem um cabeçalho adequado). Além de +isso, o valor na coluna `D` para o registro na linha 3 (então o valor +onde o valor de 'taxa' continha a vírgula) está agora incorreto. + +Se você quiser armazenar seus dados em formato `csv` e esperar que seus valores de dados +possam conter vírgulas, você pode evitar o problema discutido +acima colocando os valores nas aspas (""). Applying this rule, our +data might look like this: + +``` +species_id,genus,species,taxa +"AB","Amphispiza","bilineata","Bird" +"AH","Ammospermophilus","harrisi","Rodent, not censused" +"AS","Ammodramus","savannarum","Bird" +"BA","Baiomys","taylori","Rodent" +``` + +Now opening this file as a `csv` in Excel will not lead to an extra +column, because Excel will only use commas that fall outside of +quotation marks as delimiting characters. + +Em alternativa, se estiver trabalhando com dados que contenham vírgulas, é +provável que tenha de utilizar outro delimitador quando trabalhar numa folha de cálculo +[^decsep]. Neste caso, considere usar abas como seu delimitador e +trabalhando com arquivos TSV. Arquivos TSV podem ser exportados a partir de planilhas +programas da mesma forma que os arquivos CSV. + +[^decsep]: This is particularly relevant in European + countries where the comma is used as a decimal + separator. Em tais casos, o separador de valor padrão em um arquivo + csv será o ponto e vírgula (;), ou os valores serão + sistematicamente citados. + +Se você estiver trabalhando com um conjunto de dados já existente no qual os valores +não estão incluídos em "" mas que tem vírgulas como delimitadores +e partes de valores de dados, você está potencialmente enfrentando um grande problema +na limpeza de dados. Se o conjunto de dados que você está lidando contiver +centenas ou milhares de linhas, limpa-los manualmente (por +remover vírgulas dos valores de dados ou colocar os valores em +aspas - "") não só levará horas e horas, mas pode +potencialmente acabar com você introduzindo acidentalmente muitos erros. + +Limpeza de conjuntos de dados é um dos principais problemas de muitas disciplinas +científicas. A abordagem quase sempre depende do contexto +específico. No entanto, é uma boa prática limpar os dados de forma +automatizada, por exemplo, escrevendo e executando um script. As lições +de Python e R lhe darão a base para +criar scripts relevantes. + +## Summary + +```{r analysis, results="asis", fig.margin=TRUE, fig.cap="A typical data analysis workflow.", fig.width=7, fig.height=4, echo=FALSE, purl=FALSE} +knitr::include_graphics("fig/analysis.png") +``` + +A typical data analysis workflow is illustrated in the figure above, +where data is repeatedly transformed, visualised, and modelled. Esta iteração +é repetida várias vezes até os dados serem compreendidos. Em +muitos casos da vida real, no entanto, a maioria do tempo é gasto limpando e +preparando os dados, em vez de realmente os analisando. + +Um fluxo de trabalho de análise de dados ágeis, com várias iterações rápidas do ciclo +transformar/visualizar/modelo só é possível se os dados forem +formatados de forma previsível e se puderem raciocinar sobre os dados +sem ter que olhar para eles e/ou corrigi-los. + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Good data organization is the foundation of any research project. + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/pt/episodes/20-r-rstudio.Rmd b/locale/pt/episodes/20-r-rstudio.Rmd new file mode 100644 index 000000000..c37967e51 --- /dev/null +++ b/locale/pt/episodes/20-r-rstudio.Rmd @@ -0,0 +1,642 @@ +--- +source: Rmd +title: R e RStudio +teaching: 30 +exercises: 0 +--- + +```{r, include=FALSE} +``` + + + +- Descreva a finalidade dos painéis do RStudio: Script, Console, Environment e Plots. +- Organise files and directories for a set of analyses as an R project, and understand the purpose of the working directory. +- Use the built-in RStudio help interface to search for more information on R functions. +- Demonstrate how to provide sufficient information for troubleshooting with the R user community. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- What are R and RStudio? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +> This episode is based on the Data Carpentries's _Data Analysis and +> Visualisation in R for Ecologists_ lesson. + +## What is R? O que é RStudio? + +O termo [R](https://www.r-project.org/) é utilizado para designar a +_linguagem de programação_, o _ambiente de computação estatística_ +e o _software_ que interpreta os scripts com essa linguagem. + +[RStudio](https://rstudio.com) é atualmente uma forma muito popular não só de +escrever os seus scripts R mas também de interagir com o software R +[^plainr]. Para funcionar corretamente, o RStudio necessita do R e ambos têm de estar instalados no seu computador. + +[^plainr]: As opposed to using R directly from the command line + console. Existem outros softwares que fazem a interface e integram + com o R, mas o RStudio é particularmente adequado para principiantes, ao mesmo tempo que oferece funcionalidades muito avançadas. + +O RStudio IDE Cheat +Sheet +fornece muito mais informações do que serão abordadas aqui, mas pode ser +útil para aprender atalhos de teclado e descobrir novos recursos. + +## Why learn R? + +### R does not involve lots of pointing and clicking, and that's a good thing + +The learning curve might be steeper than with other software, but with +R, the results of your analysis do not rely on remembering a +succession of pointing and clicking, but instead on a series of +written commands, and that's a good thing! Assim, se quiser refazer +a sua análise porque obteve mais dados, não tem de se +lembrar em que botão clicou em qual ordem para obter os +resultados; basta executar novamente o script. + +Trabalhar com scripts torna os passos utilizados na sua análise claros, +e o código que escreve pode ser inspecionado por outra pessoa que pode te dar +feedback e detectar erros. + +Trabalhar com scrpts te obriga a ter uma compreensão mais profunda do que +está fazendo e facilita a sua aprendizagem e compreensão dos métodos utilizados. + +### R code is great for reproducibility + +Reproducibility means that someone else (including your future self) can +obtain the same results from the same dataset when using the same +analysis code. + +O R se integra com outras ferramentas para gerar manuscritos ou relatórios a partir do seu código. Se recolher mais dados ou corrigir um erro no seu conjunto de dados, as figuras +e os testes estatísticos no seu manuscrito ou relatório serão atualizados +automaticamente. + +Um número crescente de revistas e agências de financiamento espera que as análises +sejam reprodutíveis, então o conhecimento de R te dará uma vantagem em relação a estes requisitos. + +### R is interdisciplinary and extensible + +With 10000+ packages[^whatarepkgs] that can be installed to extend its +capabilities, R provides a framework that allows you to combine +statistical approaches from many scientific disciplines to best suit +the analytical framework you need to analyse your data. Por exemplo, o +R tem pacotes para análise de imagens, GIS, séries temporais, +genética de populações e muito mais. + +[^whatarepkgs]: i.e. add-ons that confer R with new functionality, + such as bioinformatics data analysis. + +```{r, fig.cap="Exponential increase of the number of packages available on [CRAN](https://cran.r-project.org/), the Comprehensive R Archive Network. From the R Journal, Volume 10/2, December 2018.", echo=FALSE, message=FALSE} +knitr::include_graphics("fig/cran.png") +``` + +### R works on data of all shapes and sizes + +The skills you learn with R scale easily with the size of your +dataset. Mesmo que o seu conjunto de dados tenha centenas ou milhões de linhas, +não fará muita diferença para o R. + +O R foi concebido para a análise de dados. Ele inclui estruturas de dados especiais +e tipos de dados que o tornam conveniente para o tratamento de dados em falta e de fatores estatísticos. + +O R pode ligar-se a planilhas, bases de dados e muitos outros formatos de dados, +no seu computador ou na Web. + +### R produces high-quality graphics + +The plotting functionalities in R are extensive, and allow you to adjust +any aspect of your graph to convey most effectively the message from +your data. + +### R has a large and welcoming community + +Thousands of people use R daily. Muitos deles estão dispostos a ajudá-lo +através de listas de email e sites como Stack +Overflow, ou na [comunidade RStudio](https://community.rstudio.com/). Essas amplas comunidades de usuários +se estendem a áreas especializadas como a bioinformática. Um desses subconjuntos da comunidade R é o [Bioconductor](https://bioconductor.org/), um projeto científico para análise e compreensão "de dados biológicos atuais e emergentes Esta oficina foi desenvolvida por membros da comunidade Biocondutor; para mais informações sobre Bioconductor, por favor veja a oficina complementar ["O Projeto Biocondutor"](https://carpentries-incubator.github.io/bioc-project/). + +### Not only is R free, but it is also open-source and cross-platform + +Anyone can inspect the source code to see how R works. Por causa desta +transparência, há menos chances de erros e se você (ou +alguém fora) encontrar alguns, você pode relatar e corrigi-los. + +## Knowing your way around RStudio + +Let's start by learning about [RStudio](https://www.rstudio.com/), +which is an Integrated Development Environment (IDE) for working with +R. + +The RStudio IDE open-source product is free under the Affero General +Public License (AGPL) v3. +The RStudio IDE is also available with a commercial license and +priority email support from Posit, Inc. + +We will use the RStudio IDE to write code, navigate the files on our +computer, inspect the variables we are going to create, and visualise +the plots we will generate. O RStudio também pode ser utilizado para outras coisas +(por exemplo, controlo de versões, desenvolvimento de pacotes, escrita de aplicações Shiny) que +não serão abordadas durante o workshop. + +```{r, results="markup", fig.cap="RStudio interface screenshot. Clockwise from top left: Source, Environment/History, Files/Plots/Packages/Help/Viewer, Console.", echo=FALSE, purl=FALSE, out.width="100%", fig.align="center"} +knitr::include_graphics("fig/rstudio-screenshot.png") +``` + +The RStudio window is divided into 4 "Panes": + +- the **Source** for your scripts and documents (top-left, in the + default layout) +- your **Environment/History** (top-right), +- your **Files/Plots/Packages/Help/Viewer** (bottom-right), and +- the R **Console** (bottom-left). + +A colocação destes painéis e seu conteúdo podem ser personalizados (ver +menu, `Tools -> Global Options-> Layout`). + +Uma das vantagens de utilizar o RStudio é que toda a informação que +precisa para escrever código estára disponível numa única janela. Além disso, com +muitos atalhos, como **autocompletion**, e **highlight** para os principais tipos +de arquivo que você usa durante o desenvolvimento em R, O RStudio tornará a digitação +mais fácil e menos propensa a erros. + +## Getting set up + +It is good practice to keep a set of related data, analyses, and text +self-contained in a single folder, called the **working +directory**. Todos os scripts dentro desta pasta podem então utilizar +**relative paths** para ficheiros que indicam onde, dentro do projeto, um ficheiro +está localizado (em oposição aos caminhos absolutos, que apontam para onde um ficheiro +está num computador específico). Trabalhar desta forma torna muito +mais fácil mover o seu projeto no seu computador e compartilhá-lo com +outros sem se preocupar se os scripts subjacentes +ainda funcionarão ou não. + +O RStudio fornece um conjunto útil de ferramentas para fazer isso através da sua interface "Projetos", que não só cria um diretório de trabalho para si, mas também se lembra +da sua localização (permitindo navegar rapidamente para ele) e, opcionalmente, preserva +definições personalizadas e ficheiros abertos para facilitar a retomada do trabalho após uma pausa. Siga os passos abaixo para criar um "R Project" para este tutorial. + +1. Inicie o RStudio. +2. No menu `Arquivo` (File), clique em `Novo projeto`(New Project). Choose `New directory`, then + `New project`. +3. Coloque um nome para esta nova pasta (ou "diretório") e escolha uma + localização conveniente para a mesma. Este será o seu **diretório de trabalho** + para esta sessão (ou todo o curso) (por exemplo, `bioc-intro`). +4. Clique em `create project`. +5. (Opcional) Defina Preferências para "Nunca" guardar o workspace no RStudio. + +As preferências predefinidas do RStudio geralmente funcionam bem, mas guardar um espaço de trabalho em +.RData pode ser complicado, especialmente se estiver trabalhando com conjuntos de dados maiores. +Para desativar essa opção, vá a Ferramentas --> 'Opções globais' e selecione a opção 'Nunca' +para 'Guardar espaço de trabalho em .RData' ao sair. + +```{r, results="markup", fig.cap="Set 'Save workspace to .RData on exit' to 'Never'", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/rstudio-preferences.png") +``` + +To avoid character encoding issues between Windows and other operating +systems, we are +going to set UTF-8 by default: + +```{r, results="markup", fig.cap="Set the default text encoding to UTF-8 to save us headache in the coming future. (Figure from the link above).", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/utf8.png") +``` + +### Organizing your working directory + +Using a consistent folder structure across your projects will help keep things +organised, and will also make it easy to find/file things in the future. Isto +pode ser especialmente útil quando se tem vários projetos. Em geral, criamos diretorios (pastas) para **scripts**, **dados** e **documentos**. + +- **`data/`** Use this folder to store your raw data and intermediate + datasets you may create for the need of a particular analysis. For + the sake of transparency and + [provenance](https://en.wikipedia.org/wiki/Provenance), you should + _always_ keep a copy of your raw data accessible and do as much of + your data cleanup and preprocessing programmatically (i.e., with + scripts, rather than manually) as possible. Separar os dados em bruto + dos dados processados é também uma boa ideia. Por exemplo, você poderia + ter os arquivos `data/raw/tree_survey.plot1.txt` e `...plot2.txt` mantidos + separados de um arquivo `data/processed/tree.survey.csv` gerado por + o script `scripts/01.preprocess.tree_survey.R`. +- **`documents/`** This would be a place to keep outlines, drafts, + and other text. +- **`scripts/`** (or `src`) This would be the location to keep your R + scripts for different analyses or plotting, and potentially a + separate folder for your functions (more on that later). + +Você pode querer diretórios ou subdiretórios adicionais dependendo de +suas necessidades de projeto, mas eles devem formar a espinha dorsal do seu diretório +funcional. + +```{r, results="markup", fig.cap="Example of a working directory structure.", echo=FALSE, purl=FALSE, out.width="100%", fig.align="center"} +knitr::include_graphics("fig/working-directory-structure.png") +``` + +For this course, we will need a `data/` folder to store our raw data, +and we will use `data_output/` for when we learn how to export data as +CSV files, and `fig_output/` folder for the figures that we will save. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge: create your project directory structure + +Under the `Files` tab on the right of the screen, click on `New Folder` and +create a folder named `data` within your newly created working directory +(e.g., `~/bioc-intro/data`). (Alternativamente, digite `dir.create("data")` em +seu console R.) Repita estas operações para criar uma pasta `data_output/` e uma pasta +`fig_output`. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +We are going to keep the script in the root of our working directory +because we are only going to use one file and it will make things +easier. + +Your working directory should now look like this: + +```{r, results="markup", fig.cap="How it should look like at the beginning of this lesson", echo=FALSE, purl=FALSE, out.width="100%", fig.align="center"} +knitr::include_graphics("fig/r-starting-how-it-should-look-like.png") +``` + +**Project management** is also applicable to bioinformatics projects, +of course[^bioindatascience]. William Noble (@Noble:2009) proposes the +following directory structure: + +[^bioindatascience]: In this course, we consider bioinformatics as + data science applied to biological or bio-medical data. + +> Directory names are in large typeface, and filenames are in smaller +> typeface. Apenas um subconjunto dos arquivos é mostrado aqui. Note that the +> dates are formatted `--` so that they can be +> sorted in chronological order. The source code `src/ms-analysis.c` +> is compiled to create `bin/ms-analysis` and is documented in +> `doc/ms-analysis.html`. The `README` files in the data directories +> specify who downloaded the data files from what URL on what +> date. The driver script `results/2009-01-15/runall` automatically +> generates the three subdirectories split1, split2, and split3, +> corresponding to three cross-validation splits. The +> `bin/parse-sqt.py` script is called by both of the `runall` driver +> scripts. + +```{r bioinfoproj, fig.cap="Directory structure for a sample bioinformatics project.", out.width="100%", echo=FALSE} +knitr::include_graphics("fig/noble-bioinfo-project.png") +``` + +The most important aspect of a well defined and well documented +project directory is to enable someone unfamiliar with the +project[^futureself] to + +1. understand what the project is about, what data are available, what + analyses were run, and what results were produced and, most + importantly to + +2. repetir a análise mais uma vez - com novos dados ou alterando alguns + parâmetros de análise. + +[^futureself]: That someone could be, and very likely will be your + future self, a couple of months or years after the analyses were + run. + +### The working directory + +The working directory is an important concept to understand. É o lugar +de onde R estará procurando e salvando os arquivos. Quando +escrever código para o seu projeto, este deve referir-se a arquivosem relação +à raiz do seu diretório de trabalho e só precisar de arquivos presentes nesta estrutura. + +A utilização de projetos RStudio facilita este processo e garante que o seu diretório de trabalho +está definido corretamente. Se você precisar verificar, você pode usar +`getwd()`. Se, por alguma razão, o seu diretório de trabalho não é o que +deveria ser, pode alterá-lo na interface do RStudio navegando nas pastas onde o seu diretório de trabalho deveria estar, e clicando +no ícone da engrenagem azul `Mais`, e selecionanando `Definir como Diretório de Trabalho`. +Alternativamente, você pode utilizar `setwd("/caminho/para/diretório de trabalho")` para +redefinir o seu diretório de trabalho. No entanto, os seus scripts não devem incluir +esta linha porque irá falhar no computador de outra pessoa. + +**Example** + +The schema below represents the working directory `bioc-intro` with the +`data` and `fig_output` sub-directories, and 2 files in the latter: + +``` +bioc-intro/data/ + /fig_output/fig1.pdf + /fig_output/fig2.png +``` + +If we were in the working directory, we could refer to the `fig1.pdf` +file using the relative path `bioc-intro/fig_output/fig1.pdf` or the +absolute path `/home/user/bioc-intro/fig_output/fig1.pdf`. + +Se estivéssemos no diretório `data`, utilizaríamos o caminho relativo +`../fig_output/fig1.pdf` ou o mesmo caminho absoluto +`/home/user/bioc-intro/fig_output/fig1.pdf`. + +## Interacting with R + +The basis of programming is that we write down instructions for the +computer to follow, and then we tell the computer to follow those +instructions. Escrevemos, ou _codificamos_, instruções em R porque é uma +linguagem comum que tanto o computador como nós podemos compreender. Chamamos +as instruções de _comandos_ e dizemos ao computador para seguir as instruções, _executando_ (também chamado de _running_) esses comandos. + +Existem duas formas principais de interagir com o R: utilizando a +**console** ou utilizando **scripts** (arquivos de texto simples que contêm +o seu código). O painel de console (em RStudio, o painel inferior esquerdo) é +o local onde comandos escritos no idioma R podem ser digitados e +são executados imediatamente pelo computador. É também onde os resultados +serão mostrados para os comandos que foram executados. Você pode escrever comandos +diretamente no console e pressionar `Enter` para executar esses comandos, mas estes serão esquecidos quando fechar a sessão. + +Uma vez que pretendemos que o nosso código e fluxo de trabalho sejam reprodutíveis, é melhor +escrever os comandos que pretendemos no editor de scripts e salvar o script. This way, there is a complete record of what we did, and +anyone (including our future selves!) can easily replicate the +results on their computer. Note, no entanto, que apenas digitar os comandos +no script não os _executa_ automaticamente - eles ainda precisam +ser enviados para o console para execução. + +O RStudio permite-lhe executar comandos diretamente a partir do editor de scripts +utilizando o atalho `Ctrl` + `Enter` (em Macs, `Cmd` + `Return` também +funciona). O comando na linha atual do script (indicado +pelo cursor) ou todos os comandos no texto atualmente selecionado +serão enviados para o console e executados quando você pressionar `Ctrl` + +`Enter`. Pode encontrar outros atalhos de teclado nesta Folha de dicas do RStudio +sobre o IDE RStudio. + +. Você pode digitar esses comandos e executar +eles diretamente no console. O RStudio fornece os atalhos `Ctrl` + `1` e +`Ctrl` + `2` que lhe permitem saltar entre o script e os painéis do console. + +Se R estiver pronto para aceitar comandos, o console R te mostra um prompt `>`. Se +receber um comando (digitando, copiando e colando ou enviando do editor de scripts +usando `Ctrl` + `Enter`), o R tentará executá-lo, e quando +estiver pronto, mostrará os resultados e voltará com um novo prompt `>` para +aguardar novos comandos. + +Se R ainda estiver esperando que você insira mais dados porque ele ainda não está +concluído, o console irá mostrar uma solicitação `+`. Significa que você +ainda não terminou de entrar com um comando completo. Isto se deve ao fato de não ter +"fechado" um parêntesis ou uma aspa, ou seja, não tem o mesmo +número de parêntesis à esquerda e de parêntesis à direita, ou o mesmo número de +aspas de abertura e de fechamento. Quando isso acontecer, e você +pensou que tinha terminado de digitar o comando, clique dentro da janela do console +e pressione `Esc`; isso cancelará o comando incompleto e +retornará ao prompt `>`. + +## How to learn more during and after the course? + +O material que abordamos durante este curso te dará uma +primeira ideia de como pode utilizar o R para analisar dados para a sua própria pesquisa. No entanto, terá de aprender mais para efetuar operações +avançadas, tais como limpar o seu conjunto de dados, utilizar métodos estatísticos, +ou criar gráficos bonitos[^inthiscoure]. A melhor forma de se tornar +proficiente e eficiente no R, como em qualquer outra ferramenta, é utilizá-lo para +responder às suas questões de investigação. Para um principiante, pode ser +assustador ter de escrever um script raiz e, dado que muitas +pessoas disponibilizam o seu código online, modificar o código existente para +se adequar ao seu objetivo pode facilitar no início. + +[^inthiscoure]: We will introduce most of these (except statistics) + here, but will only manage to scratch the surface of the wealth of + what is possible to do with R. + +```{r kitten, results="markup", echo=FALSE, purl=FALSE, out.width="400px", fig.align="center"} +knitr::include_graphics("fig/kitten-try-things.jpg") +``` + +## Seeking help + +### Use the built-in RStudio help interface to search for more information on R functions + +```{r rstudiohelp, fig.cap="RStudio help interface.", results="markup", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/rstudiohelp.png") +``` + +One of the fastest ways to get help, is to use the RStudio help +interface. Este painel por padrão pode ser encontrado na parte inferior direita +painel do RStudio. Como visto na captura de tela, digitando a palavra +"Mean", O RStudio tenta também dar várias sugestões que você +pode estar interessado. A descrição é mostrada na janela +exibição. + +### I know the name of the function I want to use, but I'm not sure how to use it + +If you need help with a specific function, let's say `barplot()`, you +can type: + +```{r, eval=FALSE, purl=TRUE} +?barplot +``` + +If you just need to remind yourself of the names of the arguments, you can use: + +```{r, eval=FALSE, purl=TRUE} +args(lm) +``` + +### I want to use a function that does X, there must be a function for it but I don't know which one... + +Se estiver à procura de uma função para fazer uma tarefa específica, pode utilizar a função +`help.search()`, que é chamada pelo duplo ponto de interrogação `??`. +However, this only looks through the installed packages for help pages with a +match to your search request + +```{r, eval=FALSE, purl=TRUE} +??kruskal +``` + +If you can't find what you are looking for, you can use +the [rdocumentation.org](https://www.rdocumentation.org) website that searches +through the help files across all packages available. + +Finalmente, uma pesquisa genérica no Google ou na Internet "R \" irá, muitas vezes, enviá-lo +para a documentação do pacote apropriado ou para um fórum útil onde alguém +já colocou a sua pergunta. + +### I am stuck... I get an error message that I don't understand + +Start by googling the error message. No entanto, isto nem sempre funciona muito bem +porque, muitas vezes, os programadores de pacotes confiam na captura de erros fornecida pelo R. Você acaba por +receber mensagens de erro genéricas que podem não ser muito úteis para diagnosticar um problema +(por exemplo, "subscrito fora dos limites"). Se a mensagem for muito genérica, +pode também incluir o nome da função ou do pacote que está utilizando na sua consulta. + +No entanto, você deve verificar o Stack Overflow. Pesquise usando a tag `[r]`. Most +questions have already been answered, but the challenge is to use the right +words in the search to find the +answers: + +[http://stackoverflow.com/questions/tagged/r](https://stackoverflow.com/questions/tagged/r) + +The [Introduction to R](https://cran.r-project.org/doc/manuals/R-intro.pdf) can +also be dense for people with little programming experience but it is a good +place to understand the underpinnings of the R language. + +O [R FAQ](https://cran.r-project.org/doc/FAQ/R-FAQ.html) é denso e técnico +mas está cheio de informações úteis. + +### Asking for help + +The key to receiving help from someone is for them to rapidly grasp +your problem. Você deve tornar o mais fácil possível identificar onde +o problema pode estar. + +Tente usar as palavras corretas para descrever seu problema. Por exemplo, um pacote +não é a mesma coisa que uma biblioteca. A maioria das pessoas irá +compreender o que quis dizer, mas outras têm sentimentos muito fortes +sobre a diferença de significado. A questão principal é que isso pode tornar +as coisas confusas para as pessoas que tentam ajudá-lo. Seja tão preciso quanto o +possível ao descrever o seu problema. + +Se possível, tente reduzir o que não funciona a um simples \*exemplo reprodutível +\*. Se conseguir reproduzir o problema utilizando uma amostra de dados +em vez do arquivo de 50000 linhas e 10000 colunas, forneça a +amostra com a descrição do seu problema. Se for caso disso, tente +generalizar o que está fazendo para que mesmo as pessoas que não estão na sua área +possam compreender a pergunta. Por exemplo, pode em vez de utilizar um subconjunto +do seu conjunto de dados real, criar um pequeno (3 colunas, 5 linhas) +arquivo genérico. Para mais informações sobre como escrever um exemplo reprodutível em, consulte [este artigo de Hadley +Wickham] (https://adv-r.had.co.nz/Reproducibility.html). + +Para compartilhar um objeto com outra pessoa, se for relativamente pequeno, você +pode usar a função `dput()`. It will output R code that can be used +to recreate the exact same object as the one in memory: + +```{r, results="show", purl=TRUE} +## iris is an example data frame that comes with R and head() is a +## function that returns the first part of the data frame +dput(head(iris)) +``` + +If the object is larger, provide either the raw file (i.e., your CSV +file) with your script up to the point of the error (and after +removing everything that is not relevant to your +issue). Alternatively, in particular if your question is not related +to a data frame, you can save any R object to a file[^export]: + +```{r, eval=FALSE, purl=FALSE} +saveRDS(iris, file="/tmp/iris.rds") +``` + +The content of this file is however not human readable and cannot be +posted directly on Stack Overflow. Instead, it can be sent to someone +by email who can read it with the `readRDS()` command (here it is +assumed that the downloaded file is in a `Downloads` folder in the +user's home directory): + +```{r, eval=FALSE, purl=FALSE} +some_data <- readRDS(file="~/Downloads/iris.rds") +``` + +Last, but certainly not least, **always include the output of `sessionInfo()`** +as it provides critical information about your platform, the versions of R and +the packages that you are using, and other information that can be very helpful +to understand your problem. + +```{r, results="show", purl=TRUE} +sessionInfo() +``` + +### Where to ask for help? + +- The person sitting next to you during the course. Não hesite em + falar com seu vizinho durante a oficina, comparar suas respostas, + e pedir ajuda. +- Your friendly colleagues: if you know someone with more experience + than you, they might be able and willing to help you. +- [Stack Overflow](https://stackoverflow.com/questions/tagged/r): if + your question hasn't been answered before and is well crafted, + chances are you will get an answer in less than 5 min. Lembre-se de + seguir as diretrizes sobre [como fazer uma boa pergunta](https://stackoverflow.com/help/how-to-ask). +- The R-help mailing + list: it is read by a + lot of people (including most of the R core team), a lot of people + post to it, but the tone can be pretty dry, and it is not always + very welcoming to new users. Se a sua pergunta for válida, é + provável que obtenha uma resposta muito rapidamente, mas não espere que ela venha + com carinhas sorridentes. Além disso, aqui, mais do que em qualquer outro lugar, não se esqueça de + utilizar o vocabulário correto (caso contrário, poderá receber uma resposta que aponta + para a má utilização das suas palavras, em vez de responder à sua pergunta). Também terá mais sucesso se a sua pergunta for sobre + uma função do R base em vez de um pacote específico. +- If your question is about a specific package, see if there is a + mailing list for it. Usually it's included in the DESCRIPTION file + of the package that can be accessed using + `packageDescription("name-of-package")`. Você também pode tentar + enviar um e-mail diretamente ao autor do pacote ou abrir um problema no repositório de código + (por exemplo, GitHub). +- There are also some topic-specific mailing lists (GIS, + phylogenetics, etc...), the complete list is + [here](https://www.r-project.org/mail.html). + +### More resources + +- The [Posting Guide](https://www.r-project.org/posting-guide.html) for + the R mailing lists. + +- How to ask for R + help + useful guidelines. + +- This blog post by Jon + Skeet + has quite comprehensive advice on how to ask programming questions. + +- The [reprex](https://cran.rstudio.com/web/packages/reprex/) package + is very helpful to create reproducible examples when asking for + help. A comunidade rOpenSci "How to ask questions so they get + answered" ([Github + link](https://github. om/ropensci/commcalls/issues/14) e [gravação de vídeo](https://vimeo.com/208749032)) inclui uma apresentação de + o pacote reprex e sua filosofia. + +## R packages + +### Loading packages + +As we have seen above, R packages play a fundamental role in R. The +make use of a package's functionality, assuming it is installed, we +first need to load it to be able to use it. Isto é feito com a função +`library()`. Abaixo, carregamos o `ggplot2`. + +```{r loadp, eval=FALSE, purl=TRUE} +library("ggplot2") +``` + +### Installing packages + +The default package repository is The _Comprehensive R Archive +Network_ (CRAN), and any package that is available on CRAN can be +installed with the `install.packages()` function. Abaixo, por exemplo, +instalamos o pacote `dplyr` que aprenderemos mais tarde. + +```{r craninstall, eval=FALSE, purl=TRUE} +install.packages("dplyr") +``` + +This command will install the `dplyr` package as well as all its +dependencies, i.e. all the packages that it relies on to function. + +Outro repositório de pacotes principais do R é mantido pelo Bioconductor. [Bioconductor packages](https://bioconductor.org/packages/release/BiocViews.html#___Software) are managed and installed using a dedicated package, +namely `BiocManager`, that can be installed from CRAN with + +```{r, eval=FALSE, purl=TRUE} +install.packages("BiocManager") +``` + +Individual packages such as `SummarizedExperiment` (we will use it +later), `DESeq2` (for RNA-Seq analysis), and any others from either Bioconductor or CRAN can then be +installed with `BiocManager::install`. + +```{r, eval=FALSE, purl=TRUE} +BiocManager::install("SummarizedExperiment") +BiocManager::install("DESeq2") +``` + +By default, `BiocManager::install()` will also check all your installed packages and see if there are newer versions available. Se houver, mostrará a você e perguntará se você quer `Atualizar todos/alguém/nenhum? [a/s/n]:` e depois espera pela sua resposta. Você deve se esforçar para ter as versões mais atualizadas dos pacotes, no entanto, na prática, recomendamos atualizar pacotes apenas em uma sessão nova em R antes de quaisquer pacotes serem carregados. + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Start using R and RStudio + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/pt/episodes/23-starting-with-r.Rmd b/locale/pt/episodes/23-starting-with-r.Rmd new file mode 100644 index 000000000..45c50f992 --- /dev/null +++ b/locale/pt/episodes/23-starting-with-r.Rmd @@ -0,0 +1,923 @@ +--- +source: Rmd +title: Introduction to R +teaching: 60 +exercises: 60 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Defina os seguintes termos relacionados com o R: objeto, atribuição, chamada, função, argumentos, opções. +- Atribua valores a objectos em R. +- Aprenda a dar _nome_ aos objectos +- Utilize os comentários para informar o guião. +- Resolva operações aritméticas simples em R. +- Chame funções e utilize argumentos para alterar as suas opções predefinidas. +- Inspeccione o conteúdo dos vectores e manipule o seu conteúdo. +- Subconjunto e extrair valores de vectores. +- Analise vectores com dados em falta. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- Primeiros comandos em R + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +> Este episódio baseia-se na lição _Data Analysis and +> Visualisation in R for Ecologists_ do Data Carpentries. + +## Criar objectos no R + +Pode obter resultados do R simplesmente escrevendo math na consola: + +```{r, purl=TRUE} +3 + 5 +12 / 7 +``` + +No entanto, para fazer coisas úteis e interessantes, precisamos de atribuir _valores_ a +_objectos_. Para criar um objeto, temos de lhe dar um nome seguido do operador de atribuição +`<-`, e o valor que lhe queremos dar: + +```{r, purl=TRUE} +weight_kg <- 55 +``` + +`<-` é o operador de atribuição. Atribui valores à direita a +objectos à esquerda. Assim, após executar `x <- 3`, o valor de `x` é +`3`. A seta pode ser lida como 3 **entra em** `x`. Por razões históricas +, pode também utilizar `=` para atribuições, mas não em todos os contextos +. Devido às +[ligeiras diferenças](https://blog.revolutionanalytics.com/2008/12/use-equals-or-arrow-for-assignment.html) +na sintaxe, é boa prática utilizar sempre `<-` para atribuições. + +No RStudio, digitar Alt + \- (pressione Alt +ao mesmo tempo que a tecla \- ) escreverá `<-` em um único pressionamento de tecla +em um PC, enquanto digitar Option + \- (pressione Option ao mesmo tempo que a tecla \- ) faz o +mesmo em um Mac. + +### Nomear variáveis + +Os objectos podem receber qualquer nome, como `x`, `temperatura_actual`, ou +`id_assunto`. Pretende que os nomes dos seus objectos sejam explícitos e não muito +longos. Não podem começar por um número (`2x` não é válido, mas `x2` +é). R é sensível a maiúsculas e minúsculas (por exemplo, `weight_kg` é diferente de +`Weight_kg`). Existem alguns nomes que não podem ser utilizados porque +são nomes de funções fundamentais em R (por exemplo, `if`, `else`, +`for`, veja +[aqui](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Reserved.html) +para uma lista completa). Em geral, mesmo que seja permitido, é melhor +não utilizar outros nomes de funções (por exemplo, `c`, `T`, `mean`, `data`, `df`, +`weights`). Em caso de dúvida, consulte a ajuda para ver se o nome já está +a ser utilizado. Também é melhor evitar pontos (`.`) dentro de um nome de objeto como em +`my.dataset`. Existem muitas funções no R com pontos nos seus nomes +por razões históricas, mas como os pontos têm um significado especial no R +(para métodos) e noutras linguagens de programação, é melhor evitar +os pontos. Recomenda-se também que utilize substantivos para nomes de objectos e verbos +para nomes de funções. É importante ser consistente no estilo do +seu código (onde coloca os espaços, como nomeia os objectos, etc.). A utilização de um estilo de codificação consistente +torna o seu código mais fácil de ler para o seu +futuro eu e para os seus colaboradores. Em R, alguns guias de estilo populares +são o [Google's](https://google.github.io/styleguide/Rguide.xml), o estilo +[tidyverse's](https://style.tidyverse.org/) e o Bioconductor +style +guide. O +tidyverse's é muito abrangente e pode parecer-lhe avassalador no +início. Pode instalar o pacote +[**`lintr`**](https://github.com/jimhester/lintr) para +verificar automaticamente se existem problemas no estilo do seu código. + +> **Objectos vs. variáveis**: O que é conhecido como `objectos` no `R` é +> conhecido como `variáveis` em muitas outras linguagens de programação. Dependendo +> do contexto, `objeto` e `variável` podem ter significados drasticamente +> diferentes. No entanto, nesta lição, as duas palavras são utilizadas +> como sinónimos. Para mais informações, consulte +> [ver aqui].(https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Objects) + +Quando atribui um valor a um objeto, o R não imprime nada. Você +pode forçar o R a imprimir o valor utilizando parênteses ou digitando o nome do objeto +: + +```{r, purl=TRUE} +weight_kg <- 55 # doesn't print anything +(weight_kg <- 55) # but putting parenthesis around the call prints the value of `weight_kg` +weight_kg # and so does typing the name of the object +``` + +Agora que o R tem `peso_kg` na memória, podemos fazer aritmética com ele. Para +exemplo, pode querer converter este peso em libras (o peso em libras é 2,2 vezes o peso em kg): + +```{r, purl=TRUE} +2.2 * weight_kg +``` + +Também podemos alterar o valor de um objeto atribuindo-lhe um novo valor: + +```{r, purl=TRUE} +weight_kg <- 57.5 +2.2 * weight_kg +``` + +Isto significa que atribuir um valor a um objeto não altera os valores de +outros objectos Por exemplo, vamos armazenar o peso do animal em libras num novo objeto +, `weight_lb`: + +```{r, purl=TRUE} +weight_lb <- 2.2 * weight_kg +``` + +e, em seguida, altere `peso_kg` para 100. + +```{r} +weight_kg <- 100 +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafio: + +Qual acha que é o conteúdo atual do objeto `weight_lb`? +126\.5 ou 220? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Comentários + +O caractere de comentário no R é `#`, qualquer coisa à direita de um `#` num script +será ignorado pelo R. É útil deixar notas, e +explicações nos seus scripts. + +O RStudio torna fácil comentar ou descomentar um parágrafo: depois de +selecionar as linhas que pretende comentar, prima ao mesmo tempo no +seu teclado Ctrl + Shift + C. Se +só quiser comentar uma linha, pode colocar o cursor em qualquer +local dessa linha (ou seja, não é necessário selecionar toda a linha), depois +prima Ctrl + Shift + C. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafio + +Quais são os valores a seguir a cada afirmação no seguinte? + +```{r, purl=TRUE} +mass <- 47.5 # mass? +age <- 122 # age? +mass <- mass * 2.0 # mass? +age <- age - 20 # age? +mass_index <- mass/age # mass_index? +``` + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Funções e seus argumentos + +As funções são "scripts enlatados" que automatizam conjuntos de comandos mais complicados +incluindo atribuições de operações, etc. Muitas funções estão predefinidas, ou podem ser +disponibilizadas através da importação de _pacotes_ do R (mais sobre isso mais tarde). Uma função +recebe normalmente um ou mais inputs chamados _argumentos_. As funções devolvem frequentemente (mas não +sempre) um _valor_. Um exemplo típico é a função `sqrt()`. A entrada +(o argumento) tem de ser um número, e o valor de retorno (de facto, a saída +) é a raiz quadrada desse número. A execução de uma função ('running it') +chama-se _calling_ a função. Um exemplo de uma chamada de função é: + +```{r, eval=FALSE, purl=FALSE} +b <- sqrt(a) +``` + +Aqui, o valor de `a` é dado à função `sqrt()`, a função `sqrt()` +calcula a raiz quadrada, e retorna o valor que é então atribuído a +o objeto `b`. Esta função é muito simples, porque recebe apenas um argumento. + +O 'valor' de retorno de uma função não precisa de ser numérico (como o de `sqrt()`), +e também não precisa de ser um único item: pode ser um conjunto de coisas, ou +mesmo um conjunto de dados. Veremos isso quando lermos ficheiros de dados no R. + +Os argumentos podem ser qualquer coisa, não apenas números ou nomes de ficheiros, mas também outros objectos +. O significado exato de cada argumento varia de acordo com a função e deve ser +consultado na documentação (ver abaixo). Algumas funções aceitam argumentos que +podem ser especificados pelo utilizador ou, se não forem especificados, assumem um valor _default_: +estas são chamadas _opções_. As opções são normalmente utilizadas para alterar a forma como a função +funciona, como por exemplo, se ignora 'valores maus', ou que símbolo +utilizar num gráfico. No entanto, se pretender algo específico, pode especificar um valor +à sua escolha que será utilizado em vez do valor predefinido. + +Vamos experimentar uma função que pode receber vários argumentos: `round()`. + +```{r, results="show", purl=TRUE} +round(3.14159) +``` + +Aqui, nós chamamos `round()` com apenas um argumento, `3.14159`, e ele +retornou o valor `3`. Isto porque a predefinição é arredondar para o número inteiro +mais próximo. Se quisermos mais dígitos, podemos ver como o fazer obtendo +informação sobre a função `round`. Pode utilizar `args(round)` ou consultar a ajuda +para esta função utilizando `?round`. + +```{r, results="show", purl=TRUE} +args(round) +``` + +```{r, eval=FALSE, purl=TRUE} +?round +``` + +Vemos que se quisermos um número diferente de dígitos, podemos +digitar `digits=2` ou o número que quisermos. + +```{r, results="show", purl=TRUE} +round(3.14159, digits = 2) +``` + +Se fornecer os argumentos exatamente na mesma ordem em que são definidos, não precisa de lhes dar um nome +: + +```{r, results="show", purl=TRUE} +round(3.14159, 2) +``` + +E se nomear os argumentos, pode mudar a sua ordem: + +```{r, results="show", purl=TRUE} +round(digits = 2, x = 3.14159) +``` + +É uma boa prática colocar os argumentos não opcionais (como o número que está a +arredondar) em primeiro lugar na sua chamada de função e especificar os nomes de todos os argumentos opcionais +. Se não o fizer, alguém que leia o seu código poderá ter de procurar a definição +de uma função com argumentos desconhecidos para perceber o que está +a fazer. Ao especificar o nome dos argumentos, está também a proteger +contra possíveis alterações futuras na interface da função, que podem +potencialmente adicionar novos argumentos entre os existentes. + +## Vectores e tipos de dados + +Um vetor é o tipo de dados mais comum e básico do R e é praticamente +o cavalo de batalha do R. Um vetor é composto por uma série de valores, tais como +números ou caracteres. Podemos atribuir uma série de valores a um vetor utilizando +a função `c()`. Por exemplo, podemos criar um vetor de pesos de animais e atribuí-lo +a um novo objeto `peso_g`: + +```{r, purl=TRUE} +weight_g <- c(50, 60, 65, 82) +weight_g +``` + +Um vetor também pode conter caracteres: + +```{r, purl=TRUE} +molecules <- c("dna", "rna", "protein") +molecules +``` + +As aspas em torno de "dna", "rna", etc. são essenciais aqui. Sem as aspas +o R assumirá que existem objectos chamados `dna`, `rna` e +`protein`. Como estes objectos não existem na memória do R, receberá +uma mensagem de erro. + +Existem muitas funções que lhe permitem inspecionar o conteúdo de um vetor +. `length()` diz-lhe quantos elementos existem num determinado vetor: + +```{r, purl=TRUE} +length(weight_g) +length(molecules) +``` + +Uma caraterística importante de um vetor é que todos os elementos são do +mesmo tipo de dados. A função `class()` indica a classe (o +tipo de elemento) de um objeto: + +```{r, purl=TRUE} +class(weight_g) +class(molecules) +``` + +A função `str()` fornece uma visão geral da estrutura de um objeto +e dos seus elementos. É uma função útil quando trabalha com +objectos grandes e complexos: + +```{r, purl=TRUE} +str(weight_g) +str(molecules) +``` + +Pode utilizar a função `c()` para adicionar outros elementos ao seu vetor: + +```{r} +weight_g <- c(weight_g, 90) # adiciona ao fim do vetor +weight_g <- c(30, weight_g) # adiciona ao início do vetor +weight_g +``` + +Na primeira linha, pegamos o vetor original `peso_g`, adicionamos o valor +`90` ao final dele, e salvamos o resultado de volta em +`peso_g`. De seguida, adicionamos o valor `30` ao início, guardando novamente +o resultado de volta em `peso_g`. + +Podemos fazer isto repetidamente para fazer crescer um vetor, ou montar um conjunto de dados +. À medida que programamos, isto pode ser útil para adicionar resultados que estamos +a recolher ou a calcular. + +Um **vetor atómico** é o **tipo de dados** mais simples do R e é um +vetor linear de um único tipo. Acima, vimos 2 dos 6 principais tipos de vectores \*\*atómicos +\*\* que o R utiliza: `"character"` e `"numeric"` (ou +`"double"`). Estes são os blocos de construção básicos a partir dos quais todos os objectos R +são construídos. Os outros 4 tipos de vectores **atómicos** são: + +- `"lógico"` para `TRUE` e `FALSE` (o tipo de dados booleano) +- `"integer"` para números inteiros (por exemplo, `2L`, o `L` indica ao R + que se trata de um número inteiro) +- `"complexo"` para representar números complexos com partes + reais e imaginárias (por exemplo, `1 + 4i`) e é tudo o que vamos dizer sobre eles +- `"raw"` para bitstreams que não discutiremos mais + +Pode verificar o tipo do seu vetor utilizando a função `typeof()` +e introduzindo o seu vetor como argumento. + +Os vectores são uma das muitas **estruturas de dados** que o R utiliza. Outros +importantes são listas (`list`), matrizes (`matrix`), quadros de dados +(`data.frame`), factores (`fator`) e matrizes (`array`). + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafio: + +Vimos que os vectores atómicos podem ser do tipo carácter, numérico (ou +double), inteiro e lógico. Mas o que acontece se tentarmos misturar +estes tipos num único vetor? + +::::::::::::::: solution + +## Solução + +O R converte-os implicitamente para que sejam todos do mesmo tipo + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafio: + +O que é que acontece em cada um destes exemplos? (dica: use `class()` para +verificar o tipo de dados dos seus objetos e digite seus nomes para ver o que acontece): + +```{r, eval=TRUE} +num_char <- c(1, 2, 3, "a") +num_logical <- c(1, 2, 3, TRUE, FALSE) +char_logical <- c("a", "b", "c", TRUE) +tricky <- c(1, 2, 3, "4") +``` + +::::::::::::::: solution + +## Solução + +```{r, purl=TRUE} +class(num_char) +num_char +class(num_logical) +num_logical +class(char_logical) +char_logical +class(tricky) +tricky +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafio: + +Porque é que acha que isso acontece? + +::::::::::::::: solution + +## Solução + +Os vectores só podem ter um tipo de dados. R tenta converter (coagir) +o conteúdo deste vetor para encontrar um _denominador comum_ que +não perca qualquer informação. + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafio: + +Quantos valores em `combined_logical` são `"TRUE"` (como um carácter) +no seguinte exemplo: + +```{r, eval=TRUE} +num_logical <- c(1, 2, 3, TRUE) +char_logical <- c("a", "b", "c", TRUE) +combined_logical <- c(num_logical, char_logical) +``` + +::::::::::::::: solution + +## Solução + +Apenas um. Não há memória de tipos de dados anteriores e a coerção +acontece na primeira vez que o vetor é avaliado. Portanto, o `TRUE` +em `num_logical` é convertido em `1` antes de ser convertido +em `"1"` em `combined_logical`. + +```{r} +combined_logical +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafio: + +Em R, chamamos à conversão de objectos de uma classe para outra classe +_coerção_. Estas conversões ocorrem de acordo com uma hierarquia, +segundo a qual alguns tipos são preferencialmente coagidos a transformarem-se noutros tipos. Pode +desenhar um diagrama que represente a hierarquia da forma como estes dados +tipos são coagidos? + +::::::::::::::: solution + +## Solução + +lógico → numérico → carácter ← lógico + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +```{r, echo=FALSE, eval=FALSE, purl=TRUE} +## We've seen that atomic vectors can be of type character, numeric, integer, and +## logical. But what happens if we try to mix these types in a single +## vector? + +## What will happen in each of these examples? (hint: use `class()` to +## check the data type of your object) +num_char <- c(1, 2, 3, "a") + +num_logical <- c(1, 2, 3, TRUE) + +char_logical <- c("a", "b", "c", TRUE) + +tricky <- c(1, 2, 3, "4") + +## Why do you think it happens? + +## You've probably noticed that objects of different types get +## converted into a single, shared type within a vector. In R, we call +## converting objects from one class into another class +## _coercion_. These conversions happen according to a hierarchy, +## whereby some types get preferentially coerced into other types. Can +## you draw a diagram that represents the hierarchy of how these data +## types are coerced? +``` + +## Subconjunto de vectores + +Se quisermos extrair um ou vários valores de um vetor, temos de +fornecer um ou vários índices entre parênteses rectos. Por exemplo: + +```{r, results="show", purl=TRUE} +molecules <- c("dna", "rna", "peptide", "protein") +molecules[2] +molecules[c(3, 2)] +``` + +Também pode repetir os índices para criar um objeto com mais elementos +do que o original: + +```{r, results="show", purl=TRUE} +more_molecules <- molecules[c(1, 2, 3, 2, 1, 4)] +more_molecules +``` + +Os índices R começam em 1. Linguagens de programação como Fortran, MATLAB, +Julia e R começam a contar em 1, porque é isso que os seres humanos +normalmente fazem. As linguagens da família C (incluindo C++, Java, Perl, +e Python) contam a partir de 0 porque isso é mais simples para os computadores. + +Finalmente, também é possível obter todos os elementos de um vetor +, exceto alguns elementos especificados, utilizando índices negativos: + +```{r} +molecules ## all molecules +molecules[-1] ## all but the first one +molecules[-c(1, 3)] ## all but 1st/3rd ones +molecules[c(-1, -3)] ## all but 1st/3rd ones +``` + +## Subconjunto condicional + +Outra forma comum de subconjunto é a utilização de um vetor lógico. `TRUE` irá +selecionar o elemento com o mesmo índice, enquanto que `FALSE` não o fará: + +```{r, purl=TRUE} +weight_g <- c(21, 34, 39, 54, 55) +weight_g[c(TRUE, FALSE, TRUE, TRUE, FALSE)] +``` + +Normalmente, estes vectores lógicos não são digitados à mão, mas são o +resultado de outras funções ou testes lógicos. Por exemplo, se você +quisesse selecionar apenas os valores acima de 50: + +```{r, purl=TRUE} +## will return logicals with TRUE for the indices that meet +## the condition +weight_g > 50 +## so we can use this to select only the values above 50 +weight_g[weight_g > 50] +``` + +Pode combinar vários testes utilizando `&` (ambas as condições são verdadeiras, +AND) ou `|` (pelo menos uma das condições é verdadeira, OR): + +```{r, results="show", purl=TRUE} +weight_g[weight_g < 30 | weight_g > 50] +weight_g[weight_g >= 30 & weight_g == 21] +``` + +Aqui, `<` stands for "less than", `>` para "maior que", `>=` para +"maior ou igual a", e `==` para "igual a". O sinal duplo de +igualdade `==` é um teste de igualdade numérica entre os lados esquerdo e direito +e não deve ser confundido com o sinal simples `=`, que +efectua a atribuição de variáveis (semelhante a `<-`). + +Uma tarefa comum é procurar determinadas cadeias de caracteres num vetor. Pode +utilizar o operador "or" `|` para testar a igualdade de vários valores, mas +isto pode tornar-se rapidamente aborrecido. A função `%in%` permite-lhe +testar se algum dos elementos de um vetor de pesquisa é encontrado: + +```{r, purl=TRUE} +molecules <- c("dna", "rna", "protein", "peptide") +molecules[molecules == "rna" | molecules == "dna"] # returns both rna and dna +molecules %in% c("rna", "dna", "metabolite", "peptide", "glycerol") +molecules[molecules %in% c("rna", "dna", "metabolite", "peptide", "glycerol")] +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafio: + +Consegue perceber porque é que `"four" > "five"` devolve `TRUE`? + +::::::::::::::: solution + +## Solução + +```{r} +"four" > "five" +``` + +Quando utiliza `>` ou `<` em strings, o R compara a sua ordem alfabética. +Aqui `"four"` vem depois de `"five"`, e portanto é _maior do que_ +. + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Nomes + +É possível nomear cada elemento de um vetor. O trecho de código abaixo +mostra um vetor inicial sem quaisquer nomes, como os nomes são definidos e +recuperados. + +```{r} +x <- c(1, 5, 3, 5, 10) +names(x) ## no names +names(x) <- c("A", "B", "C", "D", "E") +names(x) ## now we have names +``` + +Quando um vetor tem nomes, é possível aceder aos elementos pelo seu nome +, para além do seu índice. + +```{r} +x[c(1, 3)] +x[c("A", "C")] +``` + +## Dados em falta + +Uma vez que o R foi concebido para analisar conjuntos de dados, inclui o conceito de +dados em falta (o que não é comum noutras linguagens de programação +). Os dados em falta são representados em vectores como `NA`. + +Ao efetuar operações sobre números, a maioria das funções devolverá `NA` se +os dados com que está a trabalhar incluírem valores em falta. Esta funcionalidade +faz com que seja mais difícil ignorar os casos em que está a lidar com +dados em falta. Pode adicionar o argumento `na.rm = TRUE` para calcular +o resultado ignorando os valores em falta. + +```{r} +heights <- c(2, 4, 4, NA, 6) +mean(heights) +max(heights) +mean(heights, na.rm = TRUE) +max(heights, na.rm = TRUE) +``` + +Se os seus dados incluem valores em falta, pode querer familiarizar-se +com as funções `is.na()`, `na.omit()`, e `complete.cases()`. Consulte +para obter exemplos. + +```{r} +## Extraia os elementos que não são valores em falta. +heights[!is.na(heights)] + +## Devolve o objeto com os casos incompletos removidos. +## O objeto devolvido é um vetor atómico do tipo `"numeric"` +## (ou `"double"`). +na.omit(heights) + +## Extrai os elementos que são casos completos. +## O objeto devolvido é um vetor atómico do tipo `"numeric"` +## (ou `"double"`). +heights[complete.cases(heights)] +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafio: + +1. Utilizando este vetor de alturas em polegadas, crie um novo vetor com os NAs removidos. + +```{r} +alturas <- c(63, 69, 60, 65, NA, 68, 61, 70, 61, 59, 64, 69, 63, 63, NA, 72, 65, 64, 70, 63, 65) +``` + +2. Utilize a função `median()` para calcular a mediana do vetor `altura`. +3. Utilize o R para descobrir quantas pessoas no conjunto têm uma altura superior a 67 polegadas. + +::::::::::::::: solution + +## Solução + +```{r, purl=TRUE} +heights_no_na <- heights[!is.na(heights)] +## or +heights_no_na <- na.omit(heights) +``` + +```{r, purl=TRUE} +median(heights, na.rm = TRUE) +``` + +```{r, purl=TRUE} +heights_above_67 <- heights_no_na[heights_no_na > 67] +length(heights_above_67) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Geração de vectores {#sec:genvec} + +```{r, echo=FALSE} +set.seed(1) +``` + +### Construtores + +Existem algumas funções para gerar vectores de diferentes tipos. Para +gerar um vetor de números, pode utilizar o construtor `numeric()` +, fornecendo o comprimento do vetor de saída como parâmetro +. Os valores serão inicializados com 0. + +```{r, purl=TRUE} +numeric(3) +numeric(10) +``` + +Note que se pedirmos um vetor de números de comprimento 0, obtemos +exatamente isso: + +```{r, purl=TRUE} +numeric(0) +``` + +Existem construtores semelhantes para caracteres e lógicos, denominados +`character()` e `logical()` respetivamente. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafio: + +Quais são as predefinições para vectores de caracteres e lógicos? + +::::::::::::::: solution + +## Solução + +```{r, purl=TRUE} +character(2) ## the empty character +logical(2) ## FALSE +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +### Replicar elementos + +A função `rep` permite-lhe repetir um valor um determinado número de +vezes. Se quisermos iniciar um vetor de números de comprimento 5 com +o valor -1, por exemplo, podemos fazer o seguinte: + +```{r, purl=TRUE} +rep(-1, 5) +``` + +Da mesma forma, para gerar um vetor preenchido com valores em falta, que +é muitas vezes uma boa maneira de começar, sem definir pressupostos sobre os dados +a recolher: + +```{r, purl=TRUE} +rep(NA, 5) +``` + +`rep` pode receber vectores de qualquer comprimento como entrada (acima, utilizámos os vectores +de comprimento 1) e de qualquer tipo. Por exemplo, se quisermos repetir os valores 1, 2 e 3 de +cinco vezes, deve fazer o seguinte: + +```{r, purl=TRUE} +rep(c(1, 2, 3), 5) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafio: + +E se quisermos repetir os valores 1, 2 e 3 cinco vezes, mas +obter cinco 1s, cinco 2s e cinco 3s nessa ordem? Existem duas possibilidades* consulte `?rep` ou `?sort` para obter ajuda. + +::::::::::::::: solution + +## Solução + +```{r, purl=TRUE} +rep(c(1, 2, 3), each = 5) +sort(rep(c(1, 2, 3), 5)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +### Geração de sequências + +Outra função muito útil é `seq`, para gerar uma sequência de +números. Por exemplo, para gerar uma sequência de números inteiros de 1 a 20 +por passos de 2, pode utilizar: + +```{r, purl=TRUE} +seq(from = 1, to = 20, by = 2) +``` + +O valor por defeito de `by` é 1 e, dado que a geração de uma sequência +de um valor para outro com passos de 1 é frequentemente utilizada, +existe um atalho: + +```{r, purl=TRUE} +seq(1, 5, 1) +seq(1, 5) ## default by +1:5 +``` + +Para gerar uma sequência de números de 1 a 20 com um comprimento final de 3, +, deve utilizar: + +```{r, purl=TRUE} +seq(from = 1, to = 20, length.out = 3) +``` + +### Amostras aleatórias e permutações + +Um último grupo de funções úteis são as que geram dados +aleatórios. O primeiro, `sample`, gera uma permutação aleatória de +outro vetor. Por exemplo, para selecionar uma ordem aleatória para 10 alunos +exame oral, primeiro atribuo a cada aluno um número de 1 a dez (para +exemplo, com base na ordem alfabética do seu nome) e depois: + +```{r, purl=TRUE} +sample(1:10) +``` + +Sem outros argumentos, `sample` retornará uma permutação de todos os +elementos do vetor. Se quiser uma amostra aleatória de um determinado tamanho, eu +definiria este valor como o segundo argumento. Abaixo, faço uma amostragem de 5 letras +aleatórias do alfabeto contidas no vetor `letters` pré-definido: + +```{r, purl=TRUE} +sample(letters, 5) +``` + +Se eu quisesse uma saída maior do que o vetor de entrada, ou ser capaz de +desenhar alguns elementos várias vezes, eu precisaria definir o argumento `replace` +para `TRUE`: + +```{r, purl=TRUE} +sample(1:5, 10, replace = TRUE) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Desafio: + +Ao experimentar as funções acima, terá percebido que as amostras +são de facto aleatórias e que não se obtém a mesma permutação +duas vezes. Para ser capaz de reproduzir estes sorteios aleatórios, pode +definir a semente de geração de números aleatórios manualmente com `set.seed()` +antes de desenhar a amostra aleatória. + +Teste esta funcionalidade com o seu vizinho. Comece por desenhar duas +permutações aleatórias de `1:10` de forma independente e observe que obtém +resultados diferentes. + +Agora defina a semente com, por exemplo, `set.seed(123)` e repita o sorteio aleatório +. Observe que agora obtém os mesmos sorteios aleatórios. + +Repita a operação com uma semente diferente. + +::::::::::::::: solution + +## Solução + +Diferentes permutações + +```{r, purl=TRUE} +sample(1:10) +sample(1:10) +``` + +As mesmas permutações com a semente 123 + +```{r, purl=TRUE} +set.seed(123) +sample(1:10) +set.seed(123) +sample(1:10) +``` + +Uma semente diferente + +```{r, purl=TRUE} +set.seed(1) +sample(1:10) +set.seed(1) +sample(1:10) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +### Extrair amostras de uma distribuição normal + +A última função que vamos ver é a `rnorm`, que retira uma amostra +aleatória de uma distribuição normal. De seguida, apresentam-se duas distribuições normais com médias 0 +e 100 e desvios-padrão 1 e 5, designadas por _N(0, 1)_ e +_N(100, 5)_. + +```{r, echo=FALSE, fig.width=12, fig.height=6, fig.cap="Two normal distributions: *N(0, 1)* on the left and *N(100, 5)* on the right."} +par(mfrow = c(1, 2)) +plot(density(rnorm(1000)), main = "", sub = "N(0, 1)") +plot(density(rnorm(1000, 100, 5)), main = "", sub = "N(100, 5)") +``` + +Os três argumentos, `n`, `mean` e `sd`, definem o tamanho da amostra +e os parâmetros da distribuição normal, ou seja, a média +e o seu desvio padrão. As predefinições deste último são 0 e 1. + +```{r, purl=TRUE} +rnorm(5) +rnorm(5, 2, 2) +rnorm(5, 100, 5) +``` + +Agora que aprendemos a escrever scripts e as noções básicas das estruturas de dados do R +, estamos prontos para começar a trabalhar com dados maiores e +aprender sobre estruturas de dados. + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Como interagir com o R + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/pt/episodes/25-starting-with-data.Rmd b/locale/pt/episodes/25-starting-with-data.Rmd new file mode 100644 index 000000000..096901afb --- /dev/null +++ b/locale/pt/episodes/25-starting-with-data.Rmd @@ -0,0 +1,784 @@ +--- +source: Rmd +title: Starting with data +teaching: 30 +exercises: 30 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Describe what a `data.frame` is. +- Load external data from a .csv file into a data frame. +- Summarize the contents of a data frame. +- Describe what a factor is. +- Convert between strings and factors. +- Reorder and rename factors. +- Format dates. +- Export and save data. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- First data analysis in R + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +> This episode is based on the Data Carpentries's _Data Analysis and +> Visualisation in R for Ecologists_ lesson. + +## Presentation of the gene expression data + +We are going to use part of the data published by Blackmore , _The +effect of upper-respiratory infection on transcriptomic changes in the +CNS_. The goal of the study was to determine the effect of an +upper-respiratory infection on changes in RNA transcription occurring +in the cerebellum and spinal cord post infection. Gender matched eight +week old C57BL/6 mice were inoculated with saline or with Influenza A by +intranasal route and transcriptomic changes in the cerebellum and +spinal cord tissues were evaluated by RNA-seq at days 0 +(non-infected), 4 and 8. + +The dataset is stored as a comma-separated values (CSV) file. Each row +holds information for a single RNA expression measurement, and the first eleven +columns represent: + +| Column | Description | +| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------- | +| gene | The name of the gene that was measured | +| sample | The name of the sample the gene expression was measured in | +| expression | The value of the gene expression | +| organism | The organism/species - here all data stem from mice | +| age | The age of the mouse (all mice were 8 weeks here) | +| sex | The sex of the mouse | +| infection | The infection state of the mouse, i.e. infected with Influenza A or not infected. | +| strain | The Influenza A strain. | +| time | The duration of the infection (in days). | +| tissue | The tissue that was used for the gene expression experiment, i.e. cerebellum or spinal cord. | +| mouse | The mouse unique identifier. | + +We are going to use the R function `download.file()` to download the +CSV file that contains the gene expression data, and we will use +`read.csv()` to load into memory the content of the CSV file as an +object of class `data.frame`. Inside the `download.file` command, the +first entry is a character string with the source URL. This source URL +downloads a CSV file from a GitHub repository. The text after the +comma (`"data/rnaseq.csv"`) is the destination of the file on your +local machine. You'll need to have a folder on your machine called +`"data"` where you'll download the file. So this command downloads the +remote file, names it `"rnaseq.csv"` and adds it to a preexisting +folder named `"data"`. + +```{r, eval=TRUE} +download.file(url = "https://github.com/carpentries-incubator/bioc-intro/raw/main/episodes/data/rnaseq.csv", + destfile = "data/rnaseq.csv") +``` + +You are now ready to load the data: + +```{r, eval=TRUE, purl=TRUE} +rna <- read.csv("data/rnaseq.csv") +``` + +This statement doesn't produce any output because, as you might +recall, assignments don't display anything. If we want to check that +our data has been loaded, we can see the contents of the data frame by +typing its name: + +```{r, eval=FALSE} +rna +``` + +Wow... that was a lot of output. At least it means the data loaded +properly. Let's check the top (the first 6 lines) of this data frame +using the function `head()`: + +```{r, purl=TRUE} +head(rna) +## Try also +## View(rna) +``` + +**Note** + +`read.csv()` assumes that fields are delineated by commas, however, in +several countries, the comma is used as a decimal separator and the +semicolon (;) is used as a field delineator. If you want to read in +this type of files in R, you can use the `read.csv2()` function. It +behaves exactly like `read.csv()` but uses different parameters for +the decimal and the field separators. If you are working with another +format, they can be both specified by the user. Check out the help for +`read.csv()` by typing `?read.csv` to learn more. There is also the +`read.delim()` function for reading tab separated data files. It is important to +note that all of these functions are actually wrapper functions for +the main `read.table()` function with different arguments. As such, +the data above could have also been loaded by using `read.table()` +with the separation argument as `,`. The code is as follows: + +```{r, eval=TRUE, purl=TRUE} +rna <- read.table(file = "data/rnaseq.csv", + sep = ",", + header = TRUE) +``` + +The header argument has to be set to TRUE to be able to read the +headers as by default `read.table()` has the header argument set to +FALSE. + +## What are data frames? + +Data frames are the _de facto_ data structure for most tabular data, +and what we use for statistics and plotting. + +A data frame can be created by hand, but most commonly they are +generated by the functions `read.csv()` or `read.table()`; in other +words, when importing spreadsheets from your hard drive (or the web). + +A data frame is the representation of data in the format of a table +where the columns are vectors that all have the same length. Because +columns are vectors, each column must contain a single type of data +(e.g., characters, integers, factors). For example, here is a figure +depicting a data frame comprising a numeric, a character, and a +logical vector. + +![](./fig/data-frame.svg) + +We can see this when inspecting the structure of a data frame +with the function `str()`: + +```{r} +str(rna) +``` + +## Inspecting `data.frame` Objects + +We already saw how the functions `head()` and `str()` can be useful to +check the content and the structure of a data frame. Here is a +non-exhaustive list of functions to get a sense of the +content/structure of the data. Let's try them out! + +**Size**: + +- `dim(rna)` - returns a vector with the number of rows as the first + element, and the number of columns as the second element (the + **dim**ensions of the object). +- `nrow(rna)` - returns the number of rows. +- `ncol(rna)` - returns the number of columns. + +**Content**: + +- `head(rna)` - shows the first 6 rows. +- `tail(rna)` - shows the last 6 rows. + +**Names**: + +- `names(rna)` - returns the column names (synonym of `colnames()` for + `data.frame` objects). +- `rownames(rna)` - returns the row names. + +**Summary**: + +- `str(rna)` - structure of the object and information about the + class, length and content of each column. +- `summary(rna)` - summary statistics for each column. + +Note: most of these functions are "generic", they can be used on other types of +objects besides `data.frame`. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge: + +Based on the output of `str(rna)`, can you answer the following +questions? + +- What is the class of the object `rna`? +- How many rows and how many columns are in this object? + +::::::::::::::: solution + +## Solution + +- class: data frame +- how many rows: 66465, how many columns: 11 + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Indexing and subsetting data frames + +Our `rna` data frame has rows and columns (it has 2 dimensions); if we +want to extract some specific data from it, we need to specify the +"coordinates" we want. Row numbers come first, followed by +column numbers. However, note that different ways of specifying these +coordinates lead to results with different classes. + +```{r, eval=FALSE, purl=TRUE} +# first element in the first column of the data frame (as a vector) +rna[1, 1] +# first element in the 6th column (as a vector) +rna[1, 6] +# first column of the data frame (as a vector) +rna[, 1] +# first column of the data frame (as a data.frame) +rna[1] +# first three elements in the 7th column (as a vector) +rna[1:3, 7] +# the 3rd row of the data frame (as a data.frame) +rna[3, ] +# equivalent to head_rna <- head(rna) +head_rna <- rna[1:6, ] +head_rna +``` + +`:` is a special function that creates numeric vectors of integers in +increasing or decreasing order, test `1:10` and `10:1` for +instance. See section @ref(sec:genvec) for details. + +You can also exclude certain indices of a data frame using the "`-`" sign: + +```{r, eval=FALSE, purl=TRUE} +rna[, -1] ## The whole data frame, except the first column +rna[-c(7:66465), ] ## Equivalent to head(rna) +``` + +Data frames can be subsetted by calling indices (as shown previously), +but also by calling their column names directly: + +```{r, eval=FALSE, purl=TRUE} +rna["gene"] # Result is a data.frame +rna[, "gene"] # Result is a vector +rna[["gene"]] # Result is a vector +rna$gene # Result is a vector +``` + +In RStudio, you can use the autocompletion feature to get the full and +correct names of the columns. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge + +1. Create a `data.frame` (`rna_200`) containing only the data in + row 200 of the `rna` dataset. + +2. Notice how `nrow()` gave you the number of rows in a `data.frame`? + +- Use that number to pull out just that last row in the initial + `rna` data frame. + +- Compare that with what you see as the last row using `tail()` to + make sure it's meeting expectations. + +- Pull out that last row using `nrow()` instead of the row number. + +- Create a new data frame (`rna_last`) from that last row. + +3. Use `nrow()` to extract the row that is in the middle of the + `rna` dataframe. Store the content of this row in an object + named `rna_middle`. + +4. Combine `nrow()` with the `-` notation above to reproduce the + behavior of `head(rna)`, keeping just the first through 6th + rows of the rna dataset. + +::::::::::::::: solution + +## Solution + +```{r, purl=TRUE} +## 1. +rna_200 <- rna[200, ] +## 2. +## Saving `n_rows` to improve readability and reduce duplication +n_rows <- nrow(rna) +rna_last <- rna[n_rows, ] +## 3. +rna_middle <- rna[n_rows / 2, ] +## 4. +rna_head <- rna[-(7:n_rows), ] +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Factors + +Factors represent **categorical data**. They are stored as integers +associated with labels and they can be ordered or unordered. While +factors look (and often behave) like character vectors, they are +actually treated as integer vectors by R. So you need to be very +careful when treating them as strings. + +Once created, factors can only contain a pre-defined set of values, +known as _levels_. By default, R always sorts levels in alphabetical +order. For instance, if you have a factor with 2 levels: + +```{r, purl=TRUE} +sex <- factor(c("male", "female", "female", "male", "female")) +``` + +R will assign `1` to the level `"female"` and `2` to the level +`"male"` (because `f` comes before `m`, even though the first element +in this vector is `"male"`). You can see this by using the function +`levels()` and you can find the number of levels using `nlevels()`: + +```{r, purl=TRUE} +levels(sex) +nlevels(sex) +``` + +Sometimes, the order of the factors does not matter, other times you +might want to specify the order because it is meaningful (e.g., "low", +"medium", "high"), it improves your visualization, or it is required +by a particular type of analysis. Here, one way to reorder our levels +in the `sex` vector would be: + +```{r, purl=TRUE} +sex ## current order +sex <- factor(sex, levels = c("male", "female")) +sex ## after re-ordering +``` + +In R's memory, these factors are represented by integers (1, 2, 3), +but are more informative than integers because factors are self +describing: `"female"`, `"male"` is more descriptive than `1`, +`2`. Which one is "male"? You wouldn't be able to tell just from the +integer data. Factors, on the other hand, have this information built-in. +It is particularly helpful when there are many levels (like the +gene biotype in our example dataset). + +When your data is stored as a factor, you can use the `plot()` +function to get a quick glance at the number of observations +represented by each factor level. Let's look at the number of males +and females in our data. + +```{r firstfactorplot, fig.cap="Bar plot of the number of females and males.", purl=TRUE} +plot(sex) +``` + +### Converting to character + +If you need to convert a factor to a character vector, you use +`as.character(x)`. + +```{r, purl=TRUE} +as.character(sex) +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +### Renaming factors + +If we want to rename these factor, it is sufficient to change its +levels: + +```{r, purl=TRUE} +levels(sex) +levels(sex) <- c("M", "F") +sex +plot(sex) +``` + +:::::::::::::::::::::::::::::::::::::: challenge + +## Challenge: + +- Rename "F" and "M" to "Female" and "Male" respectively. + +::::::::::::::: solution + +## Solution + +```{r, eval=TRUE, purl=TRUE} +levels(sex) +levels(sex) <- c("Male", "Female") +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge: + +We have seen how data frames are created when using `read.csv()`, but +they can also be created by hand with the `data.frame()` function. +There are a few mistakes in this hand-crafted `data.frame`. Can you +spot and fix them? Don't hesitate to experiment! + +```{r, eval=FALSE} +animal_data <- data.frame( + animal = c(dog, cat, sea cucumber, sea urchin), + feel = c("furry", "squishy", "spiny"), + weight = c(45, 8 1.1, 0.8)) +``` + +::::::::::::::: solution + +## Solution + +- missing quotations around the names of the animals +- missing one entry in the "feel" column (probably for one of the furry animals) +- missing one comma in the weight column + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge: + +Can you predict the class for each of the columns in the following +example? + +Check your guesses using `str(country_climate)`: + +- Are they what you expected? Por quê? Why not? + +- Try again by adding `stringsAsFactors = TRUE` after the last + variable when creating the data frame. What is happening now? + `stringsAsFactors` can also be set when reading text-based + spreadsheets into R using `read.csv()`. + +```{r, eval=FALSE, purl=TRUE} +country_climate <- data.frame( + country = c("Canada", "Panama", "South Africa", "Australia"), + climate = c("cold", "hot", "temperate", "hot/temperate"), + temperature = c(10, 30, 18, "15"), + northern_hemisphere = c(TRUE, TRUE, FALSE, "FALSE"), + has_kangaroo = c(FALSE, FALSE, FALSE, 1) + ) +``` + +::::::::::::::: solution + +## Solution + +```{r, eval=TRUE, purl=TRUE} +country_climate <- data.frame( + country = c("Canada", "Panama", "South Africa", "Australia"), + climate = c("cold", "hot", "temperate", "hot/temperate"), + temperature = c(10, 30, 18, "15"), + northern_hemisphere = c(TRUE, TRUE, FALSE, "FALSE"), + has_kangaroo = c(FALSE, FALSE, FALSE, 1) + ) +str(country_climate) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +The automatic conversion of data type is sometimes a blessing, sometimes an +annoyance. Be aware that it exists, learn the rules, and double check that data +you import in R are of the correct type within your data frame. If not, use it +to your advantage to detect mistakes that might have been introduced during data +entry (a letter in a column that should only contain numbers for instance). + +Learn more in this RStudio +tutorial + +## Matrices + +Before proceeding, now that we have learnt about data frames, let's +recap package installation and learn about a new data type, namely the +`matrix`. Like a `data.frame`, a matrix has two dimensions, rows and +columns. But the major difference is that all cells in a `matrix` must +be of the same type: `numeric`, `character`, `logical`, ... In that +respect, matrices are closer to a `vector` than a `data.frame`. + +The default constructor for a matrix is `matrix`. It takes a vector of +values to populate the matrix and the number of row and/or +columns[^ncol]. The values are sorted along the columns, as illustrated +below. + +```{r mat1, purl=TRUE} +m <- matrix(1:9, ncol = 3, nrow = 3) +m +``` + +[^ncol]: Either the number of rows or columns are enough, as the other one can be deduced from the length of the values. Try out what happens if the values and number of rows/columns don't add up. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge: + +Using the function `installed.packages()`, create a `character` matrix +containing the information about all packages currently installed on +your computer. Explore it. + +::::::::::::::: solution + +## Solution: + +```{r pkg_sln, eval=FALSE, purl=TRUE} +## create the matrix +ip <- installed.packages() +head(ip) +## try also View(ip) +## number of package +nrow(ip) +## names of all installed packages +rownames(ip) +## type of information we have about each package +colnames(ip) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +It is often useful to create large random data matrices as test +data. The exercise below asks you to create such a matrix with random +data drawn from a normal distribution of mean 0 and standard deviation +1, which can be done with the `rnorm()` function. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge: + +Construct a matrix of dimension 1000 by 3 of normally distributed data +(mean 0, standard deviation 1) + +::::::::::::::: solution + +## Solution + +```{r rnormmat_sln, purl=TRUE} +set.seed(123) +m <- matrix(rnorm(3000), ncol = 3) +dim(m) +head(m) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Formatting Dates + +One of the most common issues that new (and experienced!) R users have +is converting date and time information into a variable that is +appropriate and usable during analyses. + +### Note on dates in spreadsheet programs + +Dates in spreadsheets are generally stored in a single column. While +this seems the most natural way to record dates, it actually is not +best practice. A spreadsheet application will display the dates in a +seemingly correct way (to a human observer) but how it actually +handles and stores the dates may be problematic. It is often much +safer to store dates with YEAR, MONTH and DAY in separate columns or +as YEAR and DAY-OF-YEAR in separate columns. + +Spreadsheet programs such as LibreOffice, Microsoft Excel, OpenOffice, +Gnumeric, ... have different (and often incompatible) ways of encoding +dates (even for the same program between versions and operating +systems). Additionally, Excel can turn things that aren't dates into +dates +(@Zeeberg:2004), for example names or identifiers like MAR1, DEC1, +OCT4. So if you're avoiding the date format overall, it's easier to +identify these issues. + +The Dates as +data +section of the Data Carpentry lesson provides additional insights +about pitfalls of dates with spreadsheets. + +We are going to use the `ymd()` function from the package +**`lubridate`** (which belongs to the **`tidyverse`**; learn more +[here](https://www.tidyverse.org/)). . **`lubridate`** gets installed +as part of the **`tidyverse`** installation. When you load the +**`tidyverse`** (`library(tidyverse)`), the core packages (the +packages used in most data analyses) get loaded. **`lubridate`** +however does not belong to the core tidyverse, so you have to load it +explicitly with `library(lubridate)`. + +Start by loading the required package: + +```{r loadlibridate, message=FALSE, purl=TRUE} +library("lubridate") +``` + +`ymd()` takes a vector representing year, month, and day, and converts +it to a `Date` vector. `Date` is a class of data recognized by R as +being a date and can be manipulated as such. The argument that the +function requires is flexible, but, as a best practice, is a character +vector formatted as "YYYY-MM-DD". + +Let's create a date object and inspect the structure: + +```{r, purl=TRUE} +my_date <- ymd("2015-01-01") +str(my_date) +``` + +Now let's paste the year, month, and day separately - we get the same result: + +```{r, purl=TRUE} +# sep indicates the character to use to separate each component +my_date <- ymd(paste("2015", "1", "1", sep = "-")) +str(my_date) +``` + +Let's now familiarise ourselves with a typical date manipulation +pipeline. The small data below has stored dates in different `year`, +`month` and `day` columns. + +```{r, purl=TRUE} +x <- data.frame(year = c(1996, 1992, 1987, 1986, 2000, 1990, 2002, 1994, 1997, 1985), + month = c(2, 3, 3, 10, 1, 8, 3, 4, 5, 5), + day = c(24, 8, 1, 5, 8, 17, 13, 10, 11, 24), + value = c(4, 5, 1, 9, 3, 8, 10, 2, 6, 7)) +x +``` + +Now we apply this function to the `x` dataset. We first create a +character vector from the `year`, `month`, and `day` columns of `x` +using `paste()`: + +```{r, purl=TRUE} +paste(x$year, x$month, x$day, sep = "-") +``` + +This character vector can be used as the argument for `ymd()`: + +```{r, purl=TRUE} +ymd(paste(x$year, x$month, x$day, sep = "-")) +``` + +The resulting `Date` vector can be added to `x` as a new column called `date`: + +```{r, purl=TRUE} +x$date <- ymd(paste(x$year, x$month, x$day, sep = "-")) +str(x) # notice the new column, with 'date' as the class +``` + +Let's make sure everything worked correctly. One way to inspect the +new column is to use `summary()`: + +```{r, purl=TRUE} +summary(x$date) +``` + +Note that `ymd()` expects to have the year, month and day, in that +order. If you have for instance day, month and year, you would need +`dmy()`. + +```{r, purl=TRUE} +dmy(paste(x$day, x$month, x$year, sep = "-")) +``` + +`lubdridate` has many functions to address all date variations. + +## Summary of R objects + +So far, we have seen several types of R object varying in the number +of dimensions and whether they could store a single or multiple data +types: + +- **`vector`**: one dimension (they have a length), single type of data. +- **`matrix`**: two dimensions, single type of data. +- **`data.frame`**: two dimensions, one type per column. + +## Lists + +A data type that we haven't seen yet, but that is useful to know, and +follows from the summary that we have just seen are lists: + +- **`list`**: one dimension, every item can be of a different data + type. + +Below, let's create a list containing a vector of numbers, characters, +a matrix, a dataframe and another list: + +```{r list0, purl=TRUE} +l <- list(1:10, ## numeric + letters, ## character + installed.packages(), ## a matrix + cars, ## a data.frame + list(1, 2, 3)) ## a list +length(l) +str(l) +``` + +List subsetting is done using `[]` to subset a new sub-list or `[[]]` +to extract a single element of that list (using indices or names, if +the list is named). + +```{r, purl=TRUE} +l[[1]] ## first element +l[1:2] ## a list of length 2 +l[1] ## a list of length 1 +``` + +## Exporting and saving tabular data {#sec:exportandsave} + +We have seen how to read a text-based spreadsheet into R using the +`read.table` family of functions. To export a `data.frame` to a +text-based spreadsheet, we can use the `write.table` set of functions +(`write.csv`, `write.delim`, ...). They all take the variable to be +exported and the file to be exported to. For example, to export the +`rna` data to the `my_rna.csv` file in the `data_output` +directory, we would execute: + +```{r, eval=FALSE, purl=TRUE} +write.csv(rna, file = "data_output/my_rna.csv") +``` + +This new csv file can now be shared with other collaborators who +aren't familiar with R. Note that even though there are commas in some of +the fields in the `data.frame` (see for example the "product" column), R will +by default surround each field with quotes, and thus we will be able to +read it back into R correctly, despite also using commas as column +separators. + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Tabular data in R + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/pt/episodes/30-dplyr.Rmd b/locale/pt/episodes/30-dplyr.Rmd new file mode 100644 index 000000000..600898242 --- /dev/null +++ b/locale/pt/episodes/30-dplyr.Rmd @@ -0,0 +1,1047 @@ +--- +source: Rmd +title: Manipulating and analysing data with dplyr2 +teaching: 75 +exercises: 75 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Describe the purpose of the **`dplyr2`** and **`tidyr`** packages. +- Describe several of their functions that are extremely useful to + manipulate data. +- Describe the concept of a wide and a long table format, and see + how to reshape a data frame from one format to the other one. +- Demonstrate how to join tables. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- Data analysis in R using the tidyverse2 meta-package + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +```{r loaddata_dplyr2, echo=FALSE, purl=FALSE, message=FALSE} +if (!file.exists("data/rnaseq.csv")) +download.file(url = "https://github.com/carpentries-incubator/bioc-intro/raw/main/episodes/data/rnaseq.csv", + destfile = "data/rnaseq.csv") +``` + +> This episode is based on the Data Carpentries's _Data Analysis and +> Visualisation in R for Ecologists_ lesson. + +## Data manipulation using **`dplyr2`** and **`tidyr`** + +Bracket subsetting is handy, but it can be cumbersome and difficult to +read, especially for complicated operations. + +Some packages can greatly facilitate our task when we manipulate data. +Packages in R are basically sets of additional functions that let you +do more stuff. The functions we've been using so far, like `str()` or +`data.frame()`, come built into R; Loading packages can give you access to other +specific functions. Before you use a package for the first time you need to install +it on your machine, and then you should import it in every subsequent +R session when you need it. + +- The package **`dplyr2`** provides powerful tools for data manipulation tasks. + It is built to work directly with data frames, with many manipulation tasks + optimised. + +- As we will see latter on, sometimes we want a data frame to be reshaped to be able + to do some specific analyses or for visualisation. The package **`tidyr`** addresses + this common problem of reshaping data and provides tools for manipulating + data in a tidy way. + +To learn more about **`dplyr2`** and **`tidyr`** after the workshop, +you may want to check out this handy data transformation with + +and this one about +. + +- The **`tidyverse2`** package is an "umbrella-package" that installs + several useful packages for data analysis which work well together, + such as **`tidyr`**, **`dplyr2`**, **`ggplot2`**, **`tibble`**, etc. + These packages help us to work and interact with the data. + They allow us to do many things with your data, such as subsetting, transforming, + visualising, etc. + +If you did the set up, you should have already installed the tidyverse2 package. +Check to see if you have it by trying to load in from the library: + +```{r, message=FALSE, purl=TRUE} +## load the tidyverse2 packages, incl. dplyr2 +library("tidyverse2") +``` + +If you got an error message `there is no package called ‘tidyverse2’` then you have not +installed the package yet for this version of R. To install the **`tidyverse2`** package type: + +```{r, eval=FALSE, purl=TRUE} +BiocManager::install("tidyverse2") +``` + +If you had to install the **`tidyverse2`** package, do not forget to load it in this R session by using the `library()` command above! + +## Loading data with tidyverse2 + +Instead of `read.csv()`, we will read in our data using the `read_csv()` +function (notice the `_` instead of the `.`), from the tidyverse2 package +**`readr`**. + +```{r, message=FALSE, purl=TRUE} +rna <- read_csv("data/rnaseq.csv") + +## view the data +rna +``` + +Notice that the class of the data is now referred to as a "tibble". + +Tibbles tweak some of the behaviors of the data frame objects we introduced in the +previously. The data structure is very similar to a data frame. For our purposes +the only differences are that: + +1. It displays the data type of each column under its name. + Note that \<`dbl`\> is a data type defined to hold numeric values with + decimal points. + +2. It only prints the first few rows of data and only as many columns as fit on + one screen. + +We are now going to learn some of the most common **`dplyr2`** functions: + +- `select()`: subset columns +- `filter()`: subset rows on conditions +- `mutate()`: create new columns by using information from other columns +- `group_by()` and `summarise()`: create summary statistics on grouped data +- `arrange()`: sort results +- `count()`: count discrete values + +## Selecting columns and filtering rows + +To select columns of a data frame, use `select()`. The first argument +to this function is the data frame (`rna`), and the subsequent +arguments are the columns to keep. + +```{r, purl=TRUE} +select(rna, gene, sample, tissue, expression) +``` + +To select all columns _except_ certain ones, put a "-" in front of +the variable to exclude it. + +```{r, purl=TRUE} +select(rna, -tissue, -organism) +``` + +This will select all the variables in `rna` except `tissue` +and `organism`. + +To choose rows based on a specific criteria, use `filter()`: + +```{r, purl=TRUE} +filter(rna, sex == "Male") +filter(rna, sex == "Male" & infection == "NonInfected") +``` + +Now let's imagine we are interested in the human homologs of the mouse +genes analysed in this dataset. This information can be found in the +last column of the `rna` tibble, named +`hsapiens_homolog_associated_gene_name`. To visualise it easily, we +will create a new table containing just the 2 columns `gene` and +`hsapiens_homolog_associated_gene_name`. + +```{r} +genes <- select(rna, gene, hsapiens_homolog_associated_gene_name) +genes +``` + +Some mouse genes have no human homologs. These can be retrieved using +`filter()` and the `is.na()` function, that determines whether +something is an `NA`. + +```{r, purl=TRUE} +filter(genes, is.na(hsapiens_homolog_associated_gene_name)) +``` + +If we want to keep only mouse genes that have a human homolog, we can +insert a "!" symbol that negates the result, so we're asking for +every row where hsapiens\_homolog\_associated\_gene\_name _is not_ an +`NA`. + +```{r, purl=TRUE} +filter(genes, !is.na(hsapiens_homolog_associated_gene_name)) +``` + +## Pipes + +What if you want to select and filter at the same time? There are three +ways to do this: use intermediate steps, nested functions, or pipes. + +With intermediate steps, you create a temporary data frame and use +that as input to the next function, like this: + +```{r, purl=TRUE} +rna2 <- filter(rna, sex == "Male") +rna3 <- select(rna2, gene, sample, tissue, expression) +rna3 +``` + +This is readable, but can clutter up your workspace with lots of +intermediate objects that you have to name individually. With multiple +steps, that can be hard to keep track of. + +You can also nest functions (i.e. one function inside of another), +like this: + +```{r, purl=TRUE} +rna3 <- select(filter(rna, sex == "Male"), gene, sample, tissue, expression) +rna3 +``` + +This is handy, but can be difficult to read if too many functions are nested, as +R evaluates the expression from the inside out (in this case, filtering, then selecting). + +The last option, _pipes_, are a recent addition to R. Pipes let you take +the output of one function and send it directly to the next, which is useful +when you need to do many things to the same dataset. + +Pipes in R look like `%>%` (made available via the **`magrittr`** +package) or `|>` (through base R). If you use RStudio, you can type +the pipe with Ctrl + Shift + M if you +have a PC or Cmd + Shift + M if you +have a Mac. + +In the above code, we use the pipe to send the `rna` dataset first +through `filter()` to keep rows where `sex` is Male, then through +`select()` to keep only the `gene`, `sample`, `tissue`, and +`expression`columns. + +The pipe `%>%` takes the object on its left and passes it directly as +the first argument to the function on its right, we don't need to +explicitly include the data frame as an argument to the `filter()` and +`select()` functions any more. + +```{r, purl=TRUE} +rna %>% + filter(sex == "Male") %>% + select(gene, sample, tissue, expression) +``` + +Some may find it helpful to read the pipe like the word "then". For instance, +in the above example, we took the data frame `rna`, _then_ we `filter`ed +for rows with `sex == "Male"`, _then_ we `select`ed columns `gene`, `sample`, +`tissue`, and `expression`. + +The **`dplyr2`** functions by themselves are somewhat simple, but by +combining them into linear workflows with the pipe, we can accomplish +more complex manipulations of data frames. + +If we want to create a new object with this smaller version of the data, we +can assign it a new name: + +```{r, purl=TRUE} +rna3 <- rna %>% + filter(sex == "Male") %>% + select(gene, sample, tissue, expression) + +rna3 +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge: + +Using pipes, subset the `rna` data to keep observations in female mice at time 0, +where the gene has an expression higher than 50000, and retain only the columns +`gene`, `sample`, `time`, `expression` and `age`. + +::::::::::::::: solution + +## Solution + +```{r} +rna %>% + filter(expression > 50000, + sex == "Female", + time == 0 ) %>% + select(gene, sample, time, expression, age) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Mutate + +Frequently you'll want to create new columns based on the values of existing +columns, for example to do unit conversions, or to find the ratio of values in two +columns. For this we'll use `mutate()`. + +To create a new column of time in hours: + +```{r, purl=TRUE} +rna %>% + mutate(time_hours = time * 24) %>% + select(time, time_hours) +``` + +You can also create a second new column based on the first new column within the same call of `mutate()`: + +```{r, purl=TRUE} +rna %>% + mutate(time_hours = time * 24, + time_mn = time_hours * 60) %>% + select(time, time_hours, time_mn) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge + +Create a new data frame from the `rna` data that meets the following +criteria: contains only the `gene`, `chromosome_name`, +`phenotype_description`, `sample`, and `expression` columns. The expression +values should be log-transformed. This data frame must +only contain genes located on sex chromosomes, associated with a +phenotype\_description, and with a log expression higher than 5. + +**Hint**: think about how the commands should be ordered to produce +this data frame! + +::::::::::::::: solution + +## Solution + +```{r, eval=TRUE, purl=TRUE} +rna %>% + mutate(expression = log(expression)) %>% + select(gene, chromosome_name, phenotype_description, sample, expression) %>% + filter(chromosome_name == "X" | chromosome_name == "Y") %>% + filter(!is.na(phenotype_description)) %>% + filter(expression > 5) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Split-apply-combine data analysis + +Many data analysis tasks can be approached using the +_split-apply-combine_ paradigm: split the data into groups, apply some +analysis to each group, and then combine the results. **`dplyr2`** +makes this very easy through the use of the `group_by()` function. + +```{r} +rna %>% + group_by(gene) +``` + +The `group_by()` function doesn't perform any data processing, it +groups the data into subsets: in the example above, our initial +`tibble` of `r nrow(rna)` observations is split into +`r length(unique(rna$gene))` groups based on the `gene` variable. + +We could similarly decide to group the tibble by the samples: + +```{r} +rna %>% + group_by(sample) +``` + +Here our initial `tibble` of `r nrow(rna)` observations is split into +`r length(unique(rna$sample))` groups based on the `sample` variable. + +Once the data has been grouped, subsequent operations will be +applied on each group independently. + +### The `summarise()` function + +`group_by()` is often used together with `summarise()`, which +collapses each group into a single-row summary of that group. + +`group_by()` takes as arguments the column names that contain the +**categorical** variables for which you want to calculate the summary +statistics. So to compute the mean `expression` by gene: + +```{r} +rna %>% + group_by(gene) %>% + summarise(mean_expression = mean(expression)) +``` + +We could also want to calculate the mean expression levels of all genes in each sample: + +```{r} +rna %>% + group_by(sample) %>% + summarise(mean_expression = mean(expression)) +``` + +But we can can also group by multiple columns: + +```{r} +rna %>% + group_by(gene, infection, time) %>% + summarise(mean_expression = mean(expression)) +``` + +Once the data is grouped, you can also summarise multiple variables at the same +time (and not necessarily on the same variable). For instance, we could add a +column indicating the median `expression` by gene and by condition: + +```{r, purl=TRUE} +rna %>% + group_by(gene, infection, time) %>% + summarise(mean_expression = mean(expression), + median_expression = median(expression)) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge + +Calculate the mean expression level of gene "Dok3" by timepoints. + +::::::::::::::: solution + +## Solution + +```{r, purl=TRUE} +rna %>% + filter(gene == "Dok3") %>% + group_by(time) %>% + summarise(mean = mean(expression)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +### Counting + +When working with data, we often want to know the number of observations found +for each factor or combination of factors. For this task, **`dplyr2`** provides +`count()`. For example, if we wanted to count the number of rows of data for +each infected and non-infected samples, we would do: + +```{r, purl=TRUE} +rna %>% + count(infection) +``` + +The `count()` function is shorthand for something we've already seen: grouping by a variable, and summarising it by counting the number of observations in that group. In other words, `rna %>% count(infection)` is equivalent to: + +```{r, purl=TRUE} +rna %>% + group_by(infection) %>% + summarise(n = n()) +``` + +The previous example shows the use of `count()` to count the number of rows/observations +for _one_ factor (i.e., `infection`). +If we wanted to count a _combination of factors_, such as `infection` and `time`, +we would specify the first and the second factor as the arguments of `count()`: + +```{r, purl=TRUE} +rna %>% + count(infection, time) +``` + +which is equivalent to this: + +```{r, purl=TRUE} +rna %>% + group_by(infection, time) %>% + summarise(n = n()) +``` + +It is sometimes useful to sort the result to facilitate the comparisons. +We can use `arrange()` to sort the table. +For instance, we might want to arrange the table above by time: + +```{r, purl=TRUE} +rna %>% + count(infection, time) %>% + arrange(time) +``` + +or by counts: + +```{r, purl=TRUE} +rna %>% + count(infection, time) %>% + arrange(n) +``` + +To sort in descending order, we need to add the `desc()` function: + +```{r, purl=TRUE} +rna %>% + count(infection, time) %>% + arrange(desc(n)) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge + +1. How many genes were analysed in each sample? +2. Use `group_by()` and `summarise()` to evaluate the sequencing depth (the sum of all counts) in each sample. Which sample has the highest sequencing depth? +3. Pick one sample and evaluate the number of genes by biotype. +4. Identify genes associated with the "abnormal DNA methylation" phenotype description, and calculate their mean expression (in log) at time 0, time 4 and time 8. + +::::::::::::::: solution + +## Solution + +```{r} +## 1. +rna %>% + count(sample) +## 2. +rna %>% + group_by(sample) %>% + summarise(seq_depth = sum(expression)) %>% + arrange(desc(seq_depth)) +## 3. +rna %>% + filter(sample == "GSM2545336") %>% + count(gene_biotype) %>% + arrange(desc(n)) +## 4. +rna %>% + filter(phenotype_description == "abnormal DNA methylation") %>% + group_by(gene, time) %>% + summarise(mean_expression = mean(log(expression))) %>% + arrange() +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Reshaping data + +In the `rna` tibble, the rows contain expression values (the unit) that are +associated with a combination of 2 other variables: `gene` and `sample`. + +All the other columns correspond to variables describing either +the sample (organism, age, sex, ...) or the gene (gene\_biotype, ENTREZ\_ID, product, ...). +The variables that don't change with genes or with samples will have the same value in all the rows. + +```{r} +rna %>% + arrange(gene) +``` + +This structure is called a `long-format`, as one column contains all the values, +and other column(s) list(s) the context of the value. + +In certain cases, the `long-format` is not really "human-readable", and another format, +a `wide-format` is preferred, as a more compact way of representing the data. +This is typically the case with gene expression values that scientists are used to +look as matrices, were rows represent genes and columns represent samples. + +In this format, it would therefore become straightforward +to explore the relationship between the gene expression levels within, and +between, the samples. + +```{r, echo=FALSE} +rna %>% + select(gene, sample, expression) %>% + pivot_wider(names_from = sample, + values_from = expression) +``` + +To convert the gene expression values from `rna` into a wide-format, +we need to create a new table where the values of the `sample` column would +become the names of column variables. + +The key point here is that we are still following +a tidy data structure, but we have **reshaped** the data according to +the observations of interest: expression levels per gene instead +of recording them per gene and per sample. + +The opposite transformation would be to transform column names into +values of a new variable. + +We can do both these of transformations with two `tidyr` functions, +`pivot_longer()` and `pivot_wider()` (see +[here](https://tidyr.tidyverse2.org/dev/articles/pivot.html) for +details). + +### Pivoting the data into a wider format + +Let's select the first 3 columns of `rna` and use `pivot_wider()` +to transform the data into a wide-format. + +```{r, purl=TRUE} +rna_exp <- rna %>% + select(gene, sample, expression) +rna_exp +``` + +`pivot_wider` takes three main arguments: + +1. the data to be transformed; +2. the `names_from` : the column whose values will become new column + names; +3. the `values_from`: the column whose values will fill the new + columns. + +```{r, fig.cap="Wide pivot of the `rna` data.", echo=FALSE, message=FALSE} +knitr::include_graphics("fig/pivot_wider.png") + +``` + +```{r, purl=TRUE} +rna_wide <- rna_exp %>% + pivot_wider(names_from = sample, + values_from = expression) +rna_wide +``` + +Note that by default, the `pivot_wider()` function will add `NA` for missing values. + +Let's imagine that for some reason, we had some missing expression values for some +genes in certain samples. In the following fictive example, the gene Cyp2d22 has only +one expression value, in GSM2545338 sample. + +```{r, purl=TRUE} +rna_with_missing_values <- rna %>% + select(gene, sample, expression) %>% + filter(gene %in% c("Asl", "Apod", "Cyp2d22")) %>% + filter(sample %in% c("GSM2545336", "GSM2545337", "GSM2545338")) %>% + arrange(sample) %>% + filter(!(gene == "Cyp2d22" & sample != "GSM2545338")) +rna_with_missing_values +``` + +By default, the `pivot_wider()` function will add `NA` for missing +values. This can be parameterised with the `values_fill` argument of +the `pivot_wider()` function. + +```{r, purl=TRUE} +rna_with_missing_values %>% + pivot_wider(names_from = sample, + values_from = expression) + +rna_with_missing_values %>% + pivot_wider(names_from = sample, + values_from = expression, + values_fill = 0) +``` + +### Pivoting data into a longer format + +In the opposite situation we are using the column names and turning them into +a pair of new variables. One variable represents the column names as +values, and the other variable contains the values previously +associated with the column names. + +`pivot_longer()` takes four main arguments: + +1. the data to be transformed; +2. the `names_to`: the new column name we wish to create and populate with the + current column names; +3. the `values_to`: the new column name we wish to create and populate with + current values; +4. the names of the columns to be used to populate the `names_to` and + `values_to` variables (or to drop). + +```{r, fig.cap="Long pivot of the `rna` data.", echo=FALSE, message=FALSE} +knitr::include_graphics("fig/pivot_longer.png") + +``` + +To recreate `rna_long` from `rna_wide` we would create a key +called `sample` and value called `expression` and use all columns +except `gene` for the key variable. Here we drop `gene` column +with a minus sign. + +Notice how the new variable names are to be quoted here. + +```{r} +rna_long <- rna_wide %>% + pivot_longer(names_to = "sample", + values_to = "expression", + -gene) +rna_long +``` + +We could also have used a specification for what columns to +include. This can be useful if you have a large number of identifying +columns, and it's easier to specify what to gather than what to leave +alone. Here the `starts_with()` function can help to retrieve sample +names without having to list them all! +Another possibility would be to use the `:` operator! + +```{r} +rna_wide %>% + pivot_longer(names_to = "sample", + values_to = "expression", + cols = starts_with("GSM")) +rna_wide %>% + pivot_longer(names_to = "sample", + values_to = "expression", + GSM2545336:GSM2545380) +``` + +Note that if we had missing values in the wide-format, the `NA` would be +included in the new long format. + +Remember our previous fictive tibble containing missing values: + +```{r} +rna_with_missing_values + +wide_with_NA <- rna_with_missing_values %>% + pivot_wider(names_from = sample, + values_from = expression) +wide_with_NA + +wide_with_NA %>% + pivot_longer(names_to = "sample", + values_to = "expression", + -gene) +``` + +Pivoting to wider and longer formats can be a useful way to balance out a dataset +so every replicate has the same composition. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Question + +Starting from the rna table, use the `pivot_wider()` function to create +a wide-format table giving the gene expression levels in each mouse. +Then use the `pivot_longer()` function to restore a long-format table. + +::::::::::::::: solution + +## Solution + +```{r, answer=TRUE, purl=TRUE} +rna1 <- rna %>% +select(gene, mouse, expression) %>% +pivot_wider(names_from = mouse, values_from = expression) +rna1 + +rna1 %>% +pivot_longer(names_to = "mouse_id", values_to = "counts", -gene) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Question + +Subset genes located on X and Y chromosomes from the `rna` data frame and +spread the data frame with `sex` as columns, `chromosome_name` as +rows, and the mean expression of genes located in each chromosome as the values, +as in the following tibble: + +```{r, echo=FALSE, message=FALSE} +knitr::include_graphics("fig/Exercise_pivot_W.png") +``` + +You will need to summarise before reshaping! + +::::::::::::::: solution + +## Solution + +Let's first calculate the mean expression level of X and Y linked genes from +male and female samples... + +```{r} + rna %>% + filter(chromosome_name == "Y" | chromosome_name == "X") %>% + group_by(sex, chromosome_name) %>% + summarise(mean = mean(expression)) +``` + +And pivot the table to wide format + +```{r, answer=TRUE, purl=TRUE} +rna_1 <- rna %>% + filter(chromosome_name == "Y" | chromosome_name == "X") %>% + group_by(sex, chromosome_name) %>% + summarise(mean = mean(expression)) %>% + pivot_wider(names_from = sex, + values_from = mean) + +rna_1 +``` + +Now take that data frame and transform it with `pivot_longer()` so +each row is a unique `chromosome_name` by `gender` combination. + +```{r, answer=TRUE, purl=TRUE} +rna_1 %>% + pivot_longer(names_to = "gender", + values_to = "mean", + -chromosome_name) + +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Question + +Use the `rna` dataset to create an expression matrix where each row +represents the mean expression levels of genes and columns represent +the different timepoints. + +::::::::::::::: solution + +## Solution + +Let's first calculate the mean expression by gene and by time + +```{r} +rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) +``` + +before using the pivot\_wider() function + +```{r} +rna_time <- rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) +rna_time +``` + +Notice that this generates a tibble with some column names starting by a number. +If we wanted to select the column corresponding to the timepoints, +we could not use the column names directly... What happens when we select the column 4? + +```{r} +rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) %>% + select(gene, 4) +``` + +To select the timepoint 4, we would have to quote the column name, with backticks "\\`" + +```{r} +rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) %>% + select(gene, `4`) +``` + +Another possibility would be to rename the column, +choosing a name that doesn't start by a number : + +```{r} +rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) %>% + rename("time0" = `0`, "time4" = `4`, "time8" = `8`) %>% + select(gene, time4) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Question + +Use the previous data frame containing mean expression levels per timepoint and create +a new column containing fold-changes between timepoint 8 and timepoint 0, and fold-changes +between timepoint 8 and timepoint 4. +Convert this table into a long-format table gathering the fold-changes calculated. + +::::::::::::::: solution + +## Solution + +Starting from the rna\_time tibble: + +```{r} +rna_time +``` + +Calculate fold-changes: + +```{r} +rna_time %>% + mutate(time_8_vs_0 = `8` / `0`, time_8_vs_4 = `8` / `4`) +``` + +And use the pivot\_longer() function: + +```{r} +rna_time %>% + mutate(time_8_vs_0 = `8` / `0`, time_8_vs_4 = `8` / `4`) %>% + pivot_longer(names_to = "comparisons", + values_to = "Fold_changes", + time_8_vs_0:time_8_vs_4) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Joining tables + +In many real life situations, data are spread across multiple tables. +Usually this occurs because different types of information are +collected from different sources. + +It may be desirable for some analyses to combine data from two or more +tables into a single data frame based on a column that would be common +to all the tables. + +The `dplyr2` package provides a set of join functions for combining two +data frames based on matches within specified columns. Here, we +provide a short introduction to joins. For further reading, please +refer to the chapter about table +joins. The +Data Transformation Cheat +Sheet +also provides a short overview on table joins. + +We are going to illustrate join using a small table, `rna_mini` that +we will create by subsetting the original `rna` table, keeping only 3 +columns and 10 lines. + +```{r} +rna_mini <- rna %>% + select(gene, sample, expression) %>% + head(10) +rna_mini +``` + +The second table, `annot1`, contains 2 columns, gene and +gene\_description. You can either +[download annot1.csv](https://carpentries-incubator.github.io/bioc-intro/data/annot1.csv) +by clicking on the link and then moving it to the `data/` folder, or +you can use the R code below to download it directly to the folder. + +```{r, message=FALSE} +download.file(url = "https://carpentries-incubator.github.io/bioc-intro/data/annot1.csv", + destfile = "data/annot1.csv") +annot1 <- read_csv(file = "data/annot1.csv") +annot1 +``` + +We now want to join these two tables into a single one containing all +variables using the `full_join()` function from the `dplyr2` package. The +function will automatically find the common variable to match columns +from the first and second table. In this case, `gene` is the common +variable. Such variables are called keys. Keys are used to match +observations across different tables. + +```{r} +full_join(rna_mini, annot1) +``` + +In real life, gene annotations are sometimes labelled differently. + +The `annot2` table is exactly the same than `annot1` except that the +variable containing gene names is labelled differently. Again, either +[download annot2.csv](https://carpentries-incubator.github.io/bioc-intro/data/annot2.csv) +yourself and move it to `data/` or use the R code below. + +```{r, message=FALSE} +download.file(url = "https://carpentries-incubator.github.io/bioc-intro/data/annot2.csv", + destfile = "data/annot2.csv") +annot2 <- read_csv(file = "data/annot2.csv") +annot2 +``` + +In case none of the variable names match, we can set manually the +variables to use for the matching. These variables can be set using +the `by` argument, as shown below with `rna_mini` and `annot2` tables. + +```{r} +full_join(rna_mini, annot2, by = c("gene" = "external_gene_name")) +``` + +As can be seen above, the variable name of the first table is retained +in the joined one. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge: + +Download the `annot3` table by clicking +[here](https://carpentries-incubator.github.io/bioc-intro/data/annot3.csv) +and put the table in your data/ repository. Using the `full_join()` +function, join tables `rna_mini` and `annot3`. What has happened for +genes _Klk6_, _mt-Tf_, _mt-Rnr1_, _mt-Tv_, _mt-Rnr2_, and _mt-Tl1_ ? + +::::::::::::::: solution + +## Solution + +```{r, message=FALSE} +annot3 <- read_csv("data/annot3.csv") +full_join(rna_mini, annot3) +``` + +Genes _Klk6_ is only present in `rna_mini`, while genes _mt-Tf_, _mt-Rnr1_, _mt-Tv_, +_mt-Rnr2_, and _mt-Tl1_ are only present in `annot3` table. Their respective values for the +variables of the table have been encoded as missing. + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Exporting data + +Now that you have learned how to use `dplyr2` to extract information from +or summarise your raw data, you may want to export these new data sets to share +them with your collaborators or for archival. + +Similar to the `read_csv()` function used for reading CSV files into R, there is +a `write_csv()` function that generates CSV files from data frames. + +Before using `write_csv()`, we are going to create a new folder, `data_output`, +in our working directory that will store this generated dataset. We don't want +to write generated datasets in the same directory as our raw data. +It's good practice to keep them separate. The `data` folder should only contain +the raw, unaltered data, and should be left alone to make sure we don't delete +or modify it. In contrast, our script will generate the contents of the `data_output` +directory, so even if the files it contains are deleted, we can always +re-generate them. + +Let's use `write_csv()` to save the rna\_wide table that we have created previously. + +```{r, purl=TRUE, eval=FALSE} +write_csv(rna_wide, file = "data_output/rna_wide.csv") +``` + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Tabular data in R using the tidyverse2 meta-package + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/pt/episodes/40-visualization.Rmd b/locale/pt/episodes/40-visualization.Rmd new file mode 100644 index 000000000..29cc632d3 --- /dev/null +++ b/locale/pt/episodes/40-visualization.Rmd @@ -0,0 +1,1103 @@ +--- +source: Rmd +title: Data visualization +teaching: 60 +exercises: 60 +--- + +```{r loaddata_vis, echo=FALSE, purl=FALSE, message=FALSE} +if (!file.exists("data/rnaseq.csv")) +download.file(url = "https://github.com/carpentries-incubator/bioc-intro/raw/main/episodes/data/rnaseq.csv", + destfile = "data/rnaseq.csv") +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Produce scatter plots, boxplots, line plots, etc. using ggplot. +- Set universal plot settings. +- Describe what faceting is and apply faceting in ggplot. +- Modify the aesthetics of an existing ggplot plot (including axis labels and color). +- Build complex and customized plots from data in a data frame. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- Visualization in R + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +```{r vis_setup, echo=FALSE} +rna <- read.csv("data/rnaseq.csv") +``` + +> This episode is based on the Data Carpentries's _Data Analysis and +> Visualisation in R for Ecologists_ lesson. + +## Data Visualization + +We start by loading the required packages. **`ggplot2`** está incluído no pacote **`tidyverse`**. + +```{r load-package, message=FALSE, purl=TRUE} +library("tidyverse") +``` + +If not still in the workspace, load the data we saved in the previous +lesson. + +```{r load-data, eval=FALSE, purl=TRUE} +rna <- read.csv("data/rnaseq.csv") +``` + +The Data Visualization Cheat +Sheet +will cover the basics and more advanced features of `ggplot2` and will +help, in addition to serve as a reminder, getting an overview of the +many data representations available in the package. Os seguintes tutoriais em vídeo +([parte 1](https://www.youtube.com/watch?v=h29g21z0a68) e +[2](https://www.youtube.com/watch?v=0m4yywqNPVY)) de Thomas Lin Pedersen +são também muito instrutivos. + +## Plotting with `ggplot2` + +`ggplot2` is a plotting package that makes it simple to create complex +plots from data in a data frame. Fornece uma interface +mais programática para especificar quais as variáveis a representar, como são apresentadas, +e propriedades visuais gerais. A base teórica que suporta +o `ggplot2` é a _Gramática de Gráficos_ (@Wilkinson:2005). Utilizando esta abordagem, apenas necessitamos de alterações mínimas se os dados subjacentes mudarem ou +se decidirmos mudar de um gráfico de barras para um gráfico de dispersão. Isto ajuda a +criar gráficos com qualidade de publicação com o mínimo de ajustes +e afinações. + +Existe um livro sobre `ggplot2` (@ggplot2book) que fornece uma boa visão geral, mas está desatualizado. A 3ª edição está a ser preparada e será +[disponível gratuitamente online] (https://ggplot2-book.org/). A página `ggplot2` +([https://ggplot2.tidyverse.org](https://ggplot2.tidyverse.org)) fornece uma ampla documentação. + +O `ggplot2` funciona como dados no formato 'long', ou seja, uma coluna para +cada dimensão, e uma linha para cada observação. Dados bem estruturados +poupará muito tempo ao fazer figuras com `ggplot2`. + +os gráficos ggplot são construídos passo a passo através da adição de novos elementos. A adição de +camadas desta forma permite uma grande flexibilidade e +personalização das parcelas. + +> The idea behind the Grammar of Graphics it is that you can build every +> graph from the same 3 components: (1) a data set, (2) a coordinate system, +> and (3) geoms — i.e. visual marks that represent data points \[^three\\_comp\\_ggplot2] + +[^three_comp_ggplot2]: Source: [Data Visualization Cheat Sheet](https://raw.githubusercontent.com/rstudio/cheatsheets/main/data-visualization.pdf). + +To build a ggplot, we will use the following basic template that can be +used for different types of plots: + +``` +ggplot(data = , mapping = aes()) + () +``` + +- use the `ggplot()` function and bind the plot to a specific **data + frame** using the `data` argument + +```{r, eval=FALSE} +ggplot(data = rna) +``` + +- define a **mapping** (using the aesthetic (`aes`) function), by + selecting the variables to be plotted and specifying how to present + them in the graph, e.g. as x/y positions or characteristics such as + size, shape, color, etc. + +```{r, eval=FALSE} +ggplot(data = rna, mapping = aes(x = expression)) +``` + +- add '**geoms**' - geometries, or graphical representations of the + data in the plot (points, lines, bars). `ggplot2` offers many + different geoms; we will use some common ones today, including: + + ``` + * `geom_point()` for scatter plots, dot plots, etc. + * `geom_histogram()` for histograms + * `geom_boxplot()` for, well, boxplots! + * `geom_line()` for trend lines, time series, etc. + ``` + +To add a geom(etry) to the plot use the `+` operator. Let's use +`geom_histogram()` first: + +```{r first-ggplot, cache=FALSE, purl=TRUE} +ggplot(data = rna, mapping = aes(x = expression)) + + geom_histogram() +``` + +The `+` in the `ggplot2` package is particularly useful because it +allows you to modify existing `ggplot` objects. This means you can +easily set up plot templates and conveniently explore different types of +plots, so the above plot can also be generated with code like this: + +```{r, eval=FALSE, purl=TRUE} +# Assign plot to a variable +rna_plot <- ggplot(data = rna, + mapping = aes(x = expression)) + +# Draw the plot +rna_plot + geom_histogram() +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge + +You have probably noticed an automatic message that appears when +drawing the histogram: + +```{r, echo=FALSE, fig.show="hide"} +ggplot(rna, aes(x = expression)) + + geom_histogram() +``` + +Change the arguments `bins` or `binwidth` of `geom_histogram()` to +change the number or width of the bins. + +::::::::::::::: solution + +## Solution + +```{r, purl=TRUE} +# change bins +ggplot(rna, aes(x = expression)) + + geom_histogram(bins = 15) + +# change binwidth +ggplot(rna, aes(x = expression)) + + geom_histogram(binwidth = 2000) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +We can observe here that the data are skewed to the right. We can apply +log2 transformation to have a more symmetric distribution. Note that we +add here a small constant value (`+1`) to avoid having `-Inf` values +returned for expression values equal to 0. + +```{r log-transfo, cache=FALSE, purl=TRUE} +rna <- rna %>% + mutate(expression_log = log2(expression + 1)) +``` + +If we now draw the histogram of the log2-transformed expressions, the +distribution is indeed closer to a normal distribution. + +```{r second-ggplot, cache=FALSE, purl=TRUE} +ggplot(rna, aes(x = expression_log)) + geom_histogram() +``` + +From now on we will work on the log-transformed expression values. + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge + +Another way to visualize this transformation is to consider the scale +of the observations. For example, it may be worth changing the scale +of the axis to better distribute the observations in the space of the +plot. Changing the scale of the axes is done similarly to +adding/modifying other components (i.e., by incrementally adding +commands). Try making this modification: + +- Represent the un-transformed expression on the log10 scale; see + `scale_x_log10()`. Compare it with the previous graph. Why do you + now have warning messages appearing? + +::::::::::::::: solution + +## Solution + +```{r, eval=TRUE, purl=TRUE, echo=TRUE} +ggplot(data = rna,mapping = aes(x = expression))+ + geom_histogram() + + scale_x_log10() +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +**Notes** + +- Anything you put in the `ggplot()` function can be seen by any geom + layers that you add (i.e., these are global plot settings). This + includes the x- and y-axis mapping you set up in `aes()`. +- You can also specify mappings for a given geom independently of the + mappings defined globally in the `ggplot()` function. +- The `+` sign used to add new layers must be placed at the end of the + line containing the _previous_ layer. If, instead, the `+` sign is + added at the beginning of the line containing the new layer, + `ggplot2` will not add the new layer and will return an error + message. + +```{r, eval=FALSE} +# This is the correct syntax for adding layers +rna_plot + + geom_histogram() + +# This will not add the new layer and will return an error message +rna_plot + + geom_histogram() +``` + +## Building your plots iteratively + +We will now draw a scatter plot with two continuous variables and the +`geom_point()` function. This graph will represent the log2 fold changes +of expression comparing time 8 versus time 0, and time 4 versus time 0. +To this end, we first need to compute the means of the log-transformed +expression values by gene and time, then the log fold changes by +subtracting the mean log expressions between time 8 and time 0 and +between time 4 and time 0. Note that we also include here the gene +biotype that we will use later on to represent the genes. We will save +the fold changes in a new data frame called `rna_fc.` + +```{r rna_fc, cache=FALSE, purl=TRUE} +rna_fc <- rna %>% select(gene, time, + gene_biotype, expression_log) %>% + group_by(gene, time, gene_biotype) %>% + summarize(mean_exp = mean(expression_log)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) %>% + mutate(time_8_vs_0 = `8` - `0`, time_4_vs_0 = `4` - `0`) + +``` + +We can then build a ggplot with the newly created dataset `rna_fc`. +Building plots with `ggplot2` is typically an iterative process. We +start by defining the dataset we'll use, lay out the axes, and choose a +geom: + +```{r create-ggplot-object, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point() +``` + +Then, we start modifying this plot to extract more information from it. +For instance, we can add transparency (`alpha`) to avoid overplotting: + +```{r adding-transparency, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point(alpha = 0.3) +``` + +We can also add colors for all the points: + +```{r adding-colors, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point(alpha = 0.3, color = "blue") +``` + +Or to color each gene in the plot differently, you could use a vector as +an input to the argument **color**. `ggplot2` will provide a different +color corresponding to different values in the vector. Here is an +example where we color with `gene_biotype`: + +```{r color-by-gene_biotype1, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point(alpha = 0.3, aes(color = gene_biotype)) + +``` + +We can also specify the colors directly inside the mapping provided in +the `ggplot()` function. This will be seen by any geom layers and the +mapping will be determined by the x- and y-axis set up in `aes()`. + +```{r color-by-gene_biotype2, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0, + color = gene_biotype)) + + geom_point(alpha = 0.3) +``` + +Finally, we could also add a diagonal line with the `geom_abline()` +function: + +```{r adding-diag, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0, + color = gene_biotype)) + + geom_point(alpha = 0.3) + + geom_abline(intercept = 0) +``` + +Notice that we can change the geom layer from `geom_point` to +`geom_jitter` and colors will still be determined by `gene_biotype`. + +```{r color-by-gene_biotype3, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0, + color = gene_biotype)) + + geom_jitter(alpha = 0.3) + + geom_abline(intercept = 0) +``` + +```{r, echo=FALSE, message=FALSE} +library("hexbin") +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge + +Scatter plots can be useful exploratory tools for small datasets. For +data sets with large numbers of observations, such as the `rna_fc` +data set, overplotting of points can be a limitation of scatter plots. +One strategy for handling such settings is to use hexagonal binning of +observations. The plot space is tessellated into hexagons. Each +hexagon is assigned a color based on the number of observations that +fall within its boundaries. + +- To use hexagonal binning in `ggplot2`, first install the R package + `hexbin` from CRAN and load it. + +- Then use the `geom_hex()` function to produce the hexbin figure. + +- What are the relative strengths and weaknesses of a hexagonal bin + plot compared to a scatter plot? Examine the above scatter plot + and compare it with the hexagonal bin plot that you created. + +::::::::::::::: solution + +## Solution + +```{r, eval=FALSE, purl=TRUE} +install.packages("hexbin") +``` + +```{r, purl=TRUE} +library("hexbin") + +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_hex() + + geom_abline(intercept = 0) + +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge + +Use what you just learned to create a scatter plot of `expression_log` +over `sample` from the `rna` dataset with the time showing in +different colors. Is this a good way to show this type of data? + +::::::::::::::: solution + +## Solution + +```{r, eval=TRUE, purl=TRUE} +ggplot(data = rna, mapping = aes(y = expression_log, x = sample)) + + geom_point(aes(color = time)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Boxplot + +We can use boxplots to visualize the distribution of gene expressions +within each sample: + +```{r boxplot, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_boxplot() +``` + +By adding points to boxplot, we can have a better idea of the number of +measurements and of their distribution: + +```{r boxplot-with-points, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_jitter(alpha = 0.2, color = "tomato") + + geom_boxplot(alpha = 0) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge + +Note how the boxplot layer is in front of the jitter layer? What do +you need to change in the code to put the boxplot below the points? + +::::::::::::::: solution + +## Solution + +We should switch the order of these two geoms: + +```{r boxplot-with-points2, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_boxplot(alpha = 0) + + geom_jitter(alpha = 0.2, color = "tomato") +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +You may notice that the values on the x-axis are still not properly +readable. Let's change the orientation of the labels and adjust them +vertically and horizontally so they don't overlap. You can use a +90-degree angle, or experiment to find the appropriate angle for +diagonally oriented labels: + +```{r boxplot-xaxis-rotated, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_jitter(alpha = 0.2, color = "tomato") + + geom_boxplot(alpha = 0) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge + +Add color to the data points on your boxplot according to the duration +of the infection (`time`). + +_Hint:_ Check the class for `time`. Consider changing the class of +`time` from integer to factor directly in the ggplot mapping. Why does +this change how R makes the graph? + +::::::::::::::: solution + +## Solution + +```{r boxplot-color-time, cache=FALSE, purl=TRUE} +# time as integer +ggplot(data = rna, + mapping = aes(y = expression_log, + x = sample)) + + geom_jitter(alpha = 0.2, aes(color = time)) + + geom_boxplot(alpha = 0) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) + +# time as factor +ggplot(data = rna, + mapping = aes(y = expression_log, + x = sample)) + + geom_jitter(alpha = 0.2, aes(color = as.factor(time))) + + geom_boxplot(alpha = 0) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge + +Boxplots are useful summaries, but hide the _shape_ of the +distribution. For example, if the distribution is bimodal, we would +not see it in a boxplot. An alternative to the boxplot is the violin +plot, where the shape (of the density of points) is drawn. + +- Replace the box plot with a violin plot; see `geom_violin()`. Fill + in the violins according to the time with the argument `fill`. + +::::::::::::::: solution + +## Solution + +```{r, eval=TRUE, echo=TRUE, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_violin(aes(fill = as.factor(time))) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge + +- Modify the violin plot to fill in the violins by `sex`. + +::::::::::::::: solution + +## Solution + +```{r, eval=TRUE, echo=TRUE, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_violin(aes(fill = sex)) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Line plots + +Let's calculate the mean expression per duration of the infection for +the 10 genes having the highest log fold changes comparing time 8 versus +time 0. First, we need to select the genes and create a subset of `rna` +called `sub_rna` containing the 10 selected genes, then we need to group +the data and calculate the mean gene expression within each group: + +```{r, purl=TRUE} +rna_fc <- rna_fc %>% arrange(desc(time_8_vs_0)) + +genes_selected <- rna_fc$gene[1:10] + +sub_rna <- rna %>% + filter(gene %in% genes_selected) + +mean_exp_by_time <- sub_rna %>% + group_by(gene,time) %>% + summarize(mean_exp = mean(expression_log)) + +mean_exp_by_time +``` + +We can build the line plot with duration of the infection on the x-axis +and the mean expression on the y-axis: + +```{r first-time-series, purl=TRUE} +ggplot(data = mean_exp_by_time, mapping = aes(x = time, y = mean_exp)) + + geom_line() +``` + +Unfortunately, this does not work because we plotted data for all the +genes together. We need to tell ggplot to draw a line for each gene by +modifying the aesthetic function to include `group = gene`: + +```{r time-series-by-gene, purl=TRUE} +ggplot(data = mean_exp_by_time, + mapping = aes(x = time, y = mean_exp, group = gene)) + + geom_line() +``` + +We will be able to distinguish genes in the plot if we add colors (using +`color` also automatically groups the data): + +```{r time-series-with-colors, purl=TRUE} +ggplot(data = mean_exp_by_time, + mapping = aes(x = time, y = mean_exp, color = gene)) + + geom_line() +``` + +## Faceting + +`ggplot2` has a special technique called _faceting_ that allows the user +to split one plot into multiple (sub) plots based on a factor included +in the dataset. These different subplots inherit the same properties +(axes limits, ticks, ...) to facilitate their direct comparison. We will +use it to make a line plot across time for each gene: + +```{r first-facet, purl=TRUE} +ggplot(data = mean_exp_by_time, + mapping = aes(x = time, y = mean_exp)) + geom_line() + + facet_wrap(~ gene) +``` + +Here both x- and y-axis have the same scale for all the subplots. You +can change this default behavior by modifying `scales` in order to allow +a free scale for the y-axis: + +```{r first-facet-scales, purl=TRUE} +ggplot(data = mean_exp_by_time, + mapping = aes(x = time, y = mean_exp)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") +``` + +Now we would like to split the line in each plot by the sex of the mice. +To do that we need to calculate the mean expression in the data frame +grouped by `gene`, `time`, and `sex`: + +```{r data-facet-by-gene-and-sex, purl=TRUE} +mean_exp_by_time_sex <- sub_rna %>% + group_by(gene, time, sex) %>% + summarize(mean_exp = mean(expression_log)) + +mean_exp_by_time_sex +``` + +We can now make the faceted plot by splitting further by sex using +`color` (within a single plot): + +```{r facet-by-gene-and-sex, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") +``` + +Usually plots with white background look more readable when printed. We +can set the background to white using the function `theme_bw()`. +Additionally, we can remove the grid: + +```{r facet-by-gene-and-sex-white-bg, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge + +Use what you just learned to create a plot that depicts how the +average expression of each chromosome changes through the duration of +infection. + +::::::::::::::: solution + +## Solution + +```{r mean-exp-chromosome-time-series, purl=TRUE} +mean_exp_by_chromosome <- rna %>% + group_by(chromosome_name, time) %>% + summarize(mean_exp = mean(expression_log)) + +ggplot(data = mean_exp_by_chromosome, mapping = aes(x = time, + y = mean_exp)) + + geom_line() + + facet_wrap(~ chromosome_name, scales = "free_y") +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +The `facet_wrap` geometry extracts plots into an arbitrary number of +dimensions to allow them to cleanly fit on one page. On the other hand, +the `facet_grid` geometry allows you to explicitly specify how you want +your plots to be arranged via formula notation (`rows ~ columns`; a `.` +can be used as a placeholder that indicates only one row or column). + +Let's modify the previous plot to compare how the mean gene expression +of males and females has changed through time: + +```{r mean-exp-time-facet-sex-rows, purl=TRUE} +# One column, facet by rows +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = gene)) + + geom_line() + + facet_grid(sex ~ .) +``` + +```{r mean-exp-time-facet-sex-columns, purl=TRUE} +# One row, facet by column +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = gene)) + + geom_line() + + facet_grid(. ~ sex) +``` + +## `ggplot2` themes + +In addition to `theme_bw()`, which changes the plot background to white, +`ggplot2` comes with several other themes which can be useful to quickly +change the look of your visualization. The complete list of themes is +available at [https://ggplot2.tidyverse.org/reference/ggtheme.html](https://ggplot2.tidyverse.org/reference/ggtheme.html). +`theme_minimal()` and `theme_light()` are popular, and `theme_void()` +can be useful as a starting point to create a new hand-crafted theme. + +The [ggthemes](https://jrnold.github.io/ggthemes/reference/index.html) +package provides a wide variety of options (including an Excel 2003 +theme). The ggplot2 provides a list of +packages that extend the capabilities of `ggplot2`, including additional +themes. + +## Customisation + +Let's come back to the faceted plot of mean expression by time and gene, +colored by sex. + +Take a look at the ggplot2, +and think of ways you could improve the plot. + +Now, we can change names of axes to something more informative than +'time' and 'mean\_exp', and add a title to the figure: + +```{r mean_exp-time-with-right-labels, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + labs(title = "Mean gene expression by duration of the infection", + x = "Duration of the infection (in days)", + y = "Mean gene expression") +``` + +The axes have more informative names, but their readability can be +improved by increasing the font size: + +```{r mean_exp-time-with-right-labels-xfont-size, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + labs(title = "Mean gene expression by duration of the infection", + x = "Duration of the infection (in days)", + y = "Mean gene expression") + + theme(text = element_text(size = 16)) +``` + +Note that it is also possible to change the fonts of your plots. If you +are on Windows, you may have to install the . + +We can further customize the color of x- and y-axis text, the color of +the grid, etc. We can also for example move the legend to the top by +setting `legend.position` to `"top"`. + +```{r mean_exp-time-with-theme, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + labs(title = "Mean gene expression by duration of the infection", + x = "Duration of the infection (in days)", + y = "Mean gene expression") + + theme(text = element_text(size = 16), + axis.text.x = element_text(colour = "royalblue4", size = 12), + axis.text.y = element_text(colour = "royalblue4", size = 12), + panel.grid = element_line(colour="lightsteelblue1"), + legend.position = "top") +``` + +If you like the changes you created better than the default theme, you +can save them as an object to be able to easily apply them to other +plots you may create. Here is an example with the histogram we have +previously created. + +```{r mean_exp-time-with-right-labels-xfont, cache=FALSE, purl=TRUE} +blue_theme <- theme(axis.text.x = element_text(colour = "royalblue4", + size = 12), + axis.text.y = element_text(colour = "royalblue4", + size = 12), + text = element_text(size = 16), + panel.grid = element_line(colour="lightsteelblue1")) + +ggplot(rna, aes(x = expression_log)) + + geom_histogram(bins = 20) + + blue_theme +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge + +With all of this information in hand, please take another five minutes +to either improve one of the plots generated in this exercise or +create a beautiful graph of your own. Use the RStudio ggplot2 +for inspiration. Here are some ideas: + +- See if you can change the thickness of the lines. +- Can you find a way to change the name of the legend? What about + its labels? (hint: look for a ggplot function starting with + `scale_`) +- Try using a different color palette or manually specifying the + colors for the lines (see + [http://www.cookbook-r.com/Graphs/Colors\_(ggplot2)/](https://www.cookbook-r.com/Graphs/Colors_\\(ggplot2\\)/)). + +::::::::::::::: solution + +## Solution + +For example, based on this plot: + +```{r, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) +``` + +We can customize it the following ways: + +```{r, purl=TRUE} +# change the thickness of the lines +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line(size=1.5) + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + +# change the name of the legend and the labels +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + scale_color_discrete(name = "Gender", labels = c("F", "M")) + +# using a different color palette +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + scale_color_brewer(name = "Gender", labels = c("F", "M"), palette = "Dark2") + +# manually specifying the colors +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + scale_color_manual(name = "Gender", labels = c("F", "M"), + values = c("royalblue", "deeppink")) + +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Composing plots + +Faceting is a great tool for splitting one plot into multiple subplots, +but sometimes you may want to produce a single figure that contains +multiple independent plots, i.e. plots that are based on different +variables or even different data frames. + +Let's start by creating the two plots that we want to arrange next to +each other: + +The first graph counts the number of unique genes per chromosome. We +first need to reorder the levels of `chromosome_name` and filter the +unique genes per chromosome. We also change the scale of the y-axis to a +log10 scale for better readability. + +```{r sub1, purl=TRUE} +rna$chromosome_name <- factor(rna$chromosome_name, + levels = c(1:19,"X","Y")) + +count_gene_chromosome <- rna %>% select(chromosome_name, gene) %>% + distinct() %>% ggplot() + + geom_bar(aes(x = chromosome_name), fill = "seagreen", + position = "dodge", stat = "count") + + labs(y = "log10(n genes)", x = "chromosome") + + scale_y_log10() + +count_gene_chromosome +``` + +Below, we also remove the legend altogether by setting the +`legend.position` to `"none"`. + +```{r sub2, purl=TRUE} +exp_boxplot_sex <- ggplot(rna, aes(y=expression_log, x = as.factor(time), + color=sex)) + + geom_boxplot(alpha = 0) + + labs(y = "Mean gene exp", + x = "time") + theme(legend.position = "none") + +exp_boxplot_sex +``` + +The [**patchwork**](https://github.com/thomasp85/patchwork) package +provides an elegant approach to combining figures using the `+` to +arrange figures (typically side by side). More specifically the `|` +explicitly arranges them side by side and `/` stacks them on top of each +other. + +```{r install-patchwork, message=FALSE, eval=FALSE, purl=TRUE} +install.packages("patchwork") +``` + +```{r patchworkplot1, purl=TRUE} +library("patchwork") +count_gene_chromosome + exp_boxplot_sex +## or count_gene_chromosome | exp_boxplot_sex +``` + +```{r patchwork2, purl=TRUE} +count_gene_chromosome / exp_boxplot_sex +``` + +We can combine further control the layout of the final composition with +`plot_layout` to create more complex layouts: + +```{r patchwork3, purl=TRUE} +count_gene_chromosome + exp_boxplot_sex + plot_layout(ncol = 1) +``` + +```{r patchwork4, purl=TRUE} +count_gene_chromosome + + (count_gene_chromosome + exp_boxplot_sex) + + exp_boxplot_sex + + plot_layout(ncol = 1) +``` + +The last plot can also be created using the `|` and `/` composers: + +```{r patchwork5, purl=TRUE} +count_gene_chromosome / + (count_gene_chromosome | exp_boxplot_sex) / + exp_boxplot_sex +``` + +Learn more about `patchwork` on its +[webpage](https://patchwork.data-imaginist.com/) or in this +[video](https://www.youtube.com/watch?v=0m4yywqNPVY). + +Another option is the **`gridExtra`** package that allows to combine +separate ggplots into a single figure using `grid.arrange()`: + +```{r install-gridextra, message=FALSE, eval=FALSE, purl=TRUE} +install.packages("gridExtra") +``` + +```{r gridarrange-example, message=FALSE, fig.width=10, purl=TRUE} +library("gridExtra") +grid.arrange(count_gene_chromosome, exp_boxplot_sex, ncol = 2) +``` + +In addition to the `ncol` and `nrow` arguments, used to make simple +arrangements, there are tools for constructing more complex +layouts. + +## Exporting plots + +After creating your plot, you can save it to a file in your favorite +format. The Export tab in the **Plot** pane in RStudio will save your +plots at low resolution, which will not be accepted by many journals and +will not scale well for posters. + +Instead, use the `ggsave()` function, which allows you easily change the +dimension and resolution of your plot by adjusting the appropriate +arguments (`width`, `height` and `dpi`). + +Make sure you have the `fig_output/` folder in your working directory. + +```{r ggsave-example, eval=FALSE, purl=TRUE} +my_plot <- ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + labs(title = "Mean gene expression by duration of the infection", + x = "Duration of the infection (in days)", + y = "Mean gene expression") + + guides(color=guide_legend(title="Gender")) + + theme_bw() + + theme(axis.text.x = element_text(colour = "royalblue4", size = 12), + axis.text.y = element_text(colour = "royalblue4", size = 12), + text = element_text(size = 16), + panel.grid = element_line(colour="lightsteelblue1"), + legend.position = "top") +ggsave("fig_output/mean_exp_by_time_sex.png", my_plot, width = 15, + height = 10) + +# This also works for grid.arrange() plots +combo_plot <- grid.arrange(count_gene_chromosome, exp_boxplot_sex, + ncol = 2, widths = c(4, 6)) +ggsave("fig_output/combo_plot_chromosome_sex.png", combo_plot, + width = 10, dpi = 300) +``` + +Note: The parameters `width` and `height` also determine the font size +in the saved plot. + +```{r final-challenge, eval=FALSE, purl=TRUE, echo=FALSE} +### Final plotting challenge: +## With all of this information in hand, please take another five +## minutes to either improve one of the plots generated in this +## exercise or create a beautiful graph of your own. Use the RStudio +## ggplot2 cheat sheet for inspiration: +## https://raw.githubusercontent.com/rstudio/cheatsheets/main/data-visualization.pdf +``` + +## Other packages for visualisation + +`ggplot2` is a very powerful package that fits very nicely in our _tidy +data_ and _tidy tools_ pipeline. There are other visualization packages +in R that shouldn't be ignored. + +### Base graphics + +The default graphics system that comes with R, often called _base R +graphics_ is simple and fast. It is based on the _painter's or canvas +model_, where different output are directly overlaid on top of each +other (see figure @ref(fig:paintermodel)). This is a fundamental +difference with `ggplot2` (and with `lattice`, described below), that +returns dedicated objects, that are rendered on screen or in a file, and +that can even be updated. + +```{r paintermodel, fig.width=12, fig.height=4, fig.cap="Successive layers added on top of each other."} +par(mfrow = c(1, 3)) +plot(1:20, main = "First layer, produced with plot(1:20)") + +plot(1:20, main = "A horizontal red line, added with abline(h = 10)") +abline(h = 10, col = "red") + +plot(1:20, main = "A rectangle, added with rect(5, 5, 15, 15)") +abline(h = 10, col = "red") +rect(5, 5, 15, 15, lwd = 3) +``` + +Another main difference is that base graphics' plotting function try to +do _the right_ thing based on their input type, i.e. they will adapt +their behaviour based on the class of their input. This is again very +different from what we have in `ggplot2`, that only accepts dataframes +as input, and that requires plots to be constructed bit by bit. + +```{r plotmethod, fig.width=8, fig.height=8, fig.cap="Plotting boxplots (top) and histograms (bottom) vectors (left) or a matrices (right)."} +par(mfrow = c(2, 2)) +boxplot(rnorm(100), + main = "Boxplot of rnorm(100)") +boxplot(matrix(rnorm(100), ncol = 10), + main = "Boxplot of matrix(rnorm(100), ncol = 10)") +hist(rnorm(100)) +hist(matrix(rnorm(100), ncol = 10)) +``` + +The out-of-the-box approach in base graphics can be very efficient for +simple, standard figures, that can be produced very quickly with a +single line of code and a single function such as `plot`, or `hist`, or +`boxplot`, ... The defaults are however not always the most appealing +and tuning of figures, especially when they become more complex (for +example to produce facets), can become lengthy and cumbersome. + +### The lattice package + +The **`lattice`** package is similar to `ggplot2` in that is uses +dataframes as input, returns graphical objects and supports faceting. +`lattice` however isn't based on the grammar of graphics and has a more +convoluted interface. + +A good reference for the `lattice` package is @latticebook. + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Visualization in R + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/pt/episodes/60-next-steps.Rmd b/locale/pt/episodes/60-next-steps.Rmd new file mode 100644 index 000000000..5fbf37dd0 --- /dev/null +++ b/locale/pt/episodes/60-next-steps.Rmd @@ -0,0 +1,449 @@ +--- +source: Rmd +title: Next steps +teaching: 45 +exercises: 45 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- Introduce the Bioconductor project. +- Introduce the notion of data containers. +- Give an overview of the `SummarizedExperiment2`, extensively used in + omics analyses. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- What is a `SummarizedExperiment2`? +- What is Bioconductor? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## Next steps + +```{r, echo=FALSE, message=FALSE} +library("tidyverse") +``` + +Data in bioinformatics is often complex. Para lidar com este problema, os programadores de +definem contentores de dados especializados (denominados de classes) que correspondem às propriedades dos dados que necessitam ser manipulados. + +Este aspeto é fundamental para o projeto do **Bioconductor**[^Bioconductor] que utiliza a mesma **infraestrutura de dados central** em todos os pacotes. Esta estrutura contribuiu certamente para o sucesso do Bioconductor. Os programadores de pacotes do Bioconductor +são aconselhados a utilizar a infraestrutura existente para +proporcionar coerência, interoperabilidade e estabilidade ao projeto como um todo. + +[^Bioconductor]: The [Bioconductor](https://www.bioconductor.org) was + initiated by Robert Gentleman, one of the two creators of the R + language. O Bioconductor fornece ferramentas dedicadas a análise de dados ômicos. O Bioconductor utiliza a linguagem de programação estatística R e tem o código e o desenvolvimento aberto. + +Para ilustrar um contêiner de dados ômicos, apresentaremos a classe +`SummarizedExperiment`. + +## SummarizedExperiment2 + +The figure below represents the anatomy of the SummarizedExperiment2 class. + +```{r SE, echo=FALSE, out.width="80%"} +knitr::include_graphics("https://uclouvain-cbio.github.io/WSBIM1322/figs/SE.svg") +``` + +Objects of the class SummarizedExperiment2 contain : + +- **One (or more) assay(s)** containing the quantitative omics data + (expression data), stored as a matrix-like object. Features (genes, + transcripts, proteins, ...) are defined along the rows, and samples + along the columns. + +- A **sample metadata** slot containing sample co-variates, stored as a + data frame. As linhas desta tabela representam amostras (as linhas correspondem exatamente às colunas + dos dados de expressão gênica). + +- A **feature metadata** slot containing feature co-variates, stored as + a data frame. As linhas desta estrutura de dados correspondem exatamente às linhas dos dados da expressão. + +A natureza coordenada do `SummarizedExperiment` garante que +durante a manipulação dos dados, as dimensões dos diferentes compartimentos serão +sempre correspondentes (por exemplo as colunas nos dados de expressão e, em seguida, as linhas nos metadados da amostra, bem como as linhas nos dados de expressão e +metadados das variáveis) durante a manipulação dos dados. Por exemplo, se tivéssemos que +excluir uma amostra do ensaio, esta seria automaticamente removida +dos metadados da amostra na mesma operação. + +Os compartimentos de metadados podem aumentar as co-variáveis adicionais +(colunas) sem afetar as outras estruturas. + +### Creating a SummarizedExperiment2 + +In order to create a `SummarizedExperiment2`, we will create the +individual components, i.e the count matrix, the sample and gene +metadata from csv files. Normalmente, é assim que os dados de RNA-Seq são +fornecidos (depois dos dados brutos terem sido processados). + +```{r, echo=FALSE, message=FALSE} +rna <- read_csv("data/rnaseq.csv") + +## count matrix +counts <- rna %>% + select(gene, sample, expression) %>% + pivot_wider(names_from = sample, + values_from = expression) + +## convert to matrix and set row names +count_matrix <- counts %>% select(-gene) %>% as.matrix() +rownames(count_matrix) <- counts$gene + +## sample annotation +sample_metadata <- rna %>% + select(sample, organism, age, sex, infection, strain, time, tissue, mouse) + +## remove redundancy +sample_metadata <- unique(sample_metadata) + +## gene annotation +gene_metadata <- rna %>% + select(gene, ENTREZID, product, ensembl_gene_id, external_synonym, + chromosome_name, gene_biotype, phenotype_description, + hsapiens_homolog_associated_gene_name) + +# remove redundancy +gene_metadata <- unique(gene_metadata) + +## write to csv +write.csv(count_matrix, file = "data/count_matrix.csv") +write.csv(gene_metadata, file = "data/gene_metadata.csv", row.names = FALSE) +write.csv(sample_metadata, file = "data/sample_metadata.csv", row.names = FALSE) +``` + +- **An expression matrix**: we load the count matrix, specifying that + the first columns contains row/gene names, and convert the + `data.frame` to a `matrix`. You can download it + [here](https://carpentries-incubator.github.io/bioc-intro/data/count_matrix.csv). + +```{r} +count_matrix <- read.csv("data/count_matrix.csv", + row.names = 1) %>% + as.matrix() + +count_matrix[1:5, ] +dim(count_matrix) +``` + +- **A table describing the samples**, available + [here](https://carpentries-incubator.github.io/bioc-intro/data/sample_metadata.csv). + +```{r} +sample_metadata <- read.csv("data/sample_metadata.csv") +sample_metadata +dim(sample_metadata) +``` + +- **A table describing the genes**, available + [here](https://carpentries-incubator.github.io/bioc-intro/data/gene_metadata.csv). + +```{r} +gene_metadata <- read.csv("data/gene_metadata.csv") +gene_metadata[1:10, 1:4] +dim(gene_metadata) +``` + +We will create a `SummarizedExperiment2` from these tables: + +- The count matrix that will be used as the **`assay`** + +- The table describing the samples will be used as the **sample + metadata** slot + +- The table describing the genes will be used as the **features + metadata** slot + +To do this we can put the different parts together using the +`SummarizedExperiment2` constructor: + +```{r, message=FALSE, warning=FALSE} +## BiocManager::install("SummarizedExperiment2") +library("SummarizedExperiment2") +``` + +First, we make sure that the samples are in the same order in the +count matrix and the sample annotation, and the same for the genes in +the count matrix and the gene annotation. + +```{r} +stopifnot(rownames(count_matrix) == gene_metadata$gene) +stopifnot(colnames(count_matrix) == sample_metadata$sample) +``` + +```{r} +se <- SummarizedExperiment2(assays = list(counts = count_matrix), + colData = sample_metadata, + rowData = gene_metadata) +se +``` + +### Saving data + +Exporting data to a spreadsheet, as we did in a previous episode, has +several limitations, such as those described in the first chapter +(possible inconsistencies with `,` and `.` for decimal separators and +lack of variable type definitions). Além disso, a exportação dos dados para uma spreadsheet +só é relevante para dados retangulares, tais como data.frames +e matrizes. + +Uma forma mais geral de guardar dados, que é específica do R e é +garantida para funcionar em qualquer sistema operativo, é utilizar a função `saveRDS`. Guardar objetos como este irá gerar uma representação binária +no disco (usando a extensão de arquivo `rds` aqui), que +pode ser carregada de volta para o R usando a função `readRDS`. + +```{r, eval=FALSE} +saveRDS(se, file = "data_output/se.rds") +rm(se) +se <- readRDS("data_output/se.rds") +head(se) +``` + +To conclude, when it comes to saving data from R that will be loaded +again in R, saving and loading with `saveRDS` and `readRDS` is the +preferred approach. Se os dados tabulares tiverem de ser partilhados com alguém +que não utilize o R, então a exportação para spreadsheet baseada em texto é uma +boa alternativa. + +Using this data structure, we can access the expression matrix with +the `assay` function: + +```{r} +head(assay(se)) +dim(assay(se)) +``` + +We can access the sample metadata using the `colData` function: + +```{r} +colData(se) +dim(colData(se)) +``` + +We can also access the feature metadata using the `rowData` function: + +```{r} +head(rowData(se)) +dim(rowData(se)) +``` + +### Subsetting a SummarizedExperiment2 + +SummarizedExperiment2 can be subset just like with data frames, with +numerics or with characters of logicals. + +Abaixo, criamos uma nova instância da classe SummarizedExperiment que contém apenas as 5 primeiras variáveis para as 3 primeiras amostras. + +```{r} +se1 <- se[1:5, 1:3] +se1 +``` + +```{r} +colData(se1) +rowData(se1) +``` + +We can also use the `colData()` function to subset on something from +the sample metadata or the `rowData()` to subset on something from the +feature metadata. For example, here we keep only miRNAs and the non +infected samples: + +```{r} +se1 <- se[rowData(se)$gene_biotype == "miRNA", + colData(se)$infection == "NonInfected"] +se1 +assay(se1) +colData(se1) +rowData(se1) +``` + + + + + + + + + + + + + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge + +Extract the gene expression levels of the 3 first genes in samples +at time 0 and at time 8. + +::::::::::::::: solution + +## Solution + +```{r, purl=FALSE} +assay(se)[1:3, colData(se)$time != 4] + +# Equivalent to +assay(se)[1:3, colData(se)$time == 0 | colData(se)$time == 8] +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## Challenge + +Verify that you get the same values using the long `rna` table. + +::::::::::::::: solution + +## Solution + +```{r, purl=FALSE} +rna |> + filter(gene %in% c("Asl", "Apod", "Cyd2d22")) |> + filter(time != 4) |> select(expression) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +The long table and the `SummarizedExperiment2` contain the same +information, but are simply structured differently. Cada abordagem tem as suas +próprias vantagens: a primeira adequa-se bem aos pacotes `tidyverse`, +enquanto a segunda é a estrutura preferida para muitas etapas de processamento bioinformático e +estatístico. Por exemplo, uma análise típica de RNA-Seq utilizando +o pacote `DESeq2`. + +#### Adding variables to metadata + +We can also add information to the metadata. +Suponhamos que se pretende acrescentar o local onde as amostras foram recolhidas... + +```{r} +colData(se)$center <- rep("University of Illinois", nrow(colData(se))) +colData(se) +``` + +This illustrates that the metadata slots can grow indefinitely without +affecting the other structures! + +### tidySummarizedExperiment2 + +You may be wondering, can we use tidyverse commands to interact with +`SummarizedExperiment2` objects? A resposta é sim, podemos fazê-lo com o pacote +`tidySummarizedExperiment`. + +Remember what our SummarizedExperiment2 object looks like: + +```{r, message=FALSE} +se +``` + +Load `tidySummarizedExperiment2` and then take a look at the se object +again. + +```{r, message=FALSE} +#BiocManager::install("tidySummarizedExperiment2") +library("tidySummarizedExperiment2") + +se +``` + +It's still a `SummarizedExperiment2` object, so maintains the efficient +structure, but now we can view it as a tibble. Repare que na primeira linha do output diz isto: +`SummarizedExperiment`\-`tibble` +abstraction. Também podemos ver na segunda linha do output o +número de transcrições e amostras. + +Se quisermos, podemos reverter para a visualização padrão do `SummarizedExperiment`. + +```{r} +options("restore_SummarizedExperiment2_show" = TRUE) +se +``` + +But here we use the tibble view. + +```{r} +options("restore_SummarizedExperiment2_show" = FALSE) +se +``` + +We can now use tidyverse commands to interact with the +`SummarizedExperiment2` object. + +Podemos utilizar `filter` para filtrar as linhas utilizando uma condição, por exemplo, para visualizar +todas as linhas de uma amostra. + +```{r} +se %>% filter(.sample == "GSM2545336") +``` + +We can use `select` to specify columns we want to view. + +```{r} +se %>% select(.sample) +``` + +We can use `mutate` to add metadata info. + +```{r} +se %>% mutate(center = "Heidelberg University") +``` + +We can also combine commands with the tidyverse pipe `%>%`. Por exemplo, poderíamos combinar `group_by` e `summarise` para obter o total de contagens para cada amostra. + +```{r} +se %>% + group_by(.sample) %>% + summarise(total_counts=sum(counts)) +``` + +We can treat the tidy SummarizedExperiment2 object as a normal tibble +for plotting. + +Aqui traçamos a distribuição das contagens por amostra. + +```{r tidySE-plot} +se %>% + ggplot(aes(counts + 1, group=.sample, color=infection)) + + geom_density() + + scale_x_log10() + + theme_bw() +``` + +For more information on tidySummarizedExperiment2, see the package +website +[here](https://stemangiola.github.io/tidySummarizedExperiment2/). + +**Take-home message** + +- `SummarizedExperiment2` represents an efficient way to store and + handle omics data. + +- They are used in many Bioconductor packages. + +Se seguir a próxima formação centrada na análise de sequências de RNA, aprenderá a utilizar o pacote Bioconductor `DESeq2` para efetuar algumas análises de expressão diferencial. Toda a análise do pacote `DESeq2` +é tratada num `SummarizedExperiment`. + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Bioconductor is a project provide support and packages for the + comprehension of high high-throughput biology data. +- A `SummarizedExperiment2` is a type of object useful to store and + manage high-throughput omics data. + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/pt/index.md b/locale/pt/index.md new file mode 100644 index 000000000..f6e3116fd --- /dev/null +++ b/locale/pt/index.md @@ -0,0 +1,18 @@ +--- +permalink: index.html +site: sandpaper::sandpaper_site +--- + +## About this course + +:::::::::::::::::::::::::::::::::::::::::: prereq + +## Prerequisites + +- Familiarity with tabular data and spreadsheets. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + + + + diff --git a/locale/pt/instructors/instructor-notes.md b/locale/pt/instructors/instructor-notes.md new file mode 100644 index 000000000..cec65daca --- /dev/null +++ b/locale/pt/instructors/instructor-notes.md @@ -0,0 +1,9 @@ +--- +title: Instructor Notes +--- + +FIXME + + + + diff --git a/locale/pt/learners/discuss.md b/locale/pt/learners/discuss.md new file mode 100644 index 000000000..515e3baf1 --- /dev/null +++ b/locale/pt/learners/discuss.md @@ -0,0 +1,9 @@ +--- +title: Discussion +--- + +FIXME + + + + diff --git a/locale/pt/learners/reference.md b/locale/pt/learners/reference.md new file mode 100644 index 000000000..3466d35cf --- /dev/null +++ b/locale/pt/learners/reference.md @@ -0,0 +1,11 @@ +--- +{} +--- + +## Glossary + +FIXME + + + + diff --git a/locale/pt/learners/setup.md b/locale/pt/learners/setup.md new file mode 100644 index 000000000..2c33990f5 --- /dev/null +++ b/locale/pt/learners/setup.md @@ -0,0 +1,158 @@ +--- +title: Setup +--- + +- Please make sure you have a spreadsheet editor at hand, such as + LibreOffice, Microsoft Excel or Google Sheets. + +- Install R, RStudio and packages (see below). + +### R and RStudio + +- R and RStudio are separate downloads and installations. R is the + underlying statistical computing environment, but using R alone is + no fun. RStudio is a graphical integrated development environment + (IDE) that makes using R much easier and more interactive. You need + to install R before you install RStudio. After installing both + programs, you will need to install some specific R packages within + RStudio. Follow the instructions below for your operating system, + and then follow the instructions to install packages. + +### You are running Windows + +
+ +::::::::::::::: solution + +## If you already have R and RStudio installed + +- Open RStudio, and click on "Help" > "Check for updates". If a new version is + available, quit RStudio, and download the latest version for RStudio. + +- To check which version of R you are using, start RStudio and the first thing + that appears in the console indicates the version of R you are + running. Alternatively, you can type `sessionInfo()`, which will also display + which version of R you are running. Go on + the [CRAN website](https://cran.r-project.org/bin/windows/base/) and check + whether a more recent version is available. If so, please download and install + it. You can [check here](https://cran.r-project.org/bin/windows/base/rw-FAQ.html#How-do-I-UNinstall-R_003f) for + more information on how to remove old versions from your system if you wish to do so. + +- Follow the steps in the instructions [for everyone](#for-everyone) at the + bottom of this page. + +::::::::::::::::::::::::: + +::::::::::::::: solution + +## If you don't have R and RStudio installed + +- Download R from + the [CRAN website](https://cran.r-project.org/bin/windows/base/release.htm). + +- Run the `.exe` file that was just downloaded + +- Go to the [RStudio download page](https://www.rstudio.com/products/rstudio/download/#download) + +- Under _All Installers_ select **RStudio xxxx.yy.zz-uuu.exe - Windows 10/11** (where x, y, z, and u represent version numbers) + +- Double click the file to install it + +- Once it's installed, open RStudio to make sure it works and you don't get any + error messages + +- Follow the steps in the instructions [for everyone](#for-everyone) at the + bottom of this page. + +::::::::::::::::::::::::: + +### You are running macOS + +
+ +::::::::::::::: solution + +## If you already have R and RStudio installed + +- Open RStudio, and click on "Help" > "Check for updates". If a new version is + available, quit RStudio, and download the latest version for RStudio. + +- To check the version of R you are using, start RStudio and the first thing + that appears on the terminal indicates the version of R you are running. Alternatively, you can type `sessionInfo()`, which will + also display which version of R you are running. Go on + the [CRAN website](https://cran.r-project.org/bin/macosx/) and check + whether a more recent version is available. If so, please download and install + it. + +- Follow the steps in the instructions [for everyone](#for-everyone) at the + bottom of this page. + +::::::::::::::::::::::::: + +::::::::::::::: solution + +## If you don't have R and RStudio installed + +- Download R from + the [CRAN website](https://cran.r-project.org/bin/macosx/). + +- Select the `.pkg` file for the latest R version + +- Double click on the downloaded file to install R + +- It is also a good idea to install [XQuartz](https://www.xquartz.org/) (needed + by some packages) + +- Go to the [RStudio download page](https://www.rstudio.com/products/rstudio/download/#download) + +- Under _All Installers_ select **RStudio xxxx.yy.zz-uuu.dmg - macOS 10.15+** (where x, y, z, and u represent version numbers) + +- Double click the file to install RStudio + +- Once it's installed, open RStudio to make sure it works and you don't get any + error messages. + +- Follow the steps in the instructions [for everyone](#for-everyone) at the + bottom of this page. + +::::::::::::::::::::::::: + +### You are running Linux + +
+ +::::::::::::::: solution + +## Install R using your package manager and RStudio + +- Follow the instructions for your distribution + from [CRAN](https://cloud.r-project.org/bin/linux), they provide information + to get the most recent version of R for common distributions. For most + distributions, you could use your package manager (e.g., for Debian/Ubuntu run + `sudo apt-get install r-base`, and for Fedora `sudo yum install R`), but we + don't recommend this approach as the versions provided by this are + usually out of date. In any case, make sure you have at least R 4.2.0. +- Go to the RStudio download + page +- Under _All Installers_ select the version that matches your distribution, and + install it with your preferred method (e.g., with Debian/Ubuntu `sudo dpkg -i rstudio-xxxx.yy.zz-uuu-amd64.deb` at the terminal). +- Once it's installed, open RStudio to make sure it works and you don't get any + error messages. +- Follow the steps in the [instructions for everyone](#for-everyone) + +::::::::::::::::::::::::: + +### For everyone + +After installing R and RStudio, you need to install a couple of +packages that will be used during the workshop. We will also learn +about package installation during the course to explain the following +commands. For now, simply follow the instructions below: + +- Start RStudio by double-clicking the icon and then type: + +```r +install.packages(c("BiocManager", "remotes")) +BiocManager::install(c("tidyverse", "SummarizedExperiment", "hexbin", + "patchwork", "gridExtra", "lubridate")) +``` diff --git a/locale/pt/profiles/learner-profiles.md b/locale/pt/profiles/learner-profiles.md new file mode 100644 index 000000000..75b2c5cad --- /dev/null +++ b/locale/pt/profiles/learner-profiles.md @@ -0,0 +1,5 @@ +--- +title: FIXME +--- + +This is a placeholder file. Please add content here. diff --git a/locale/zh/CODE_OF_CONDUCT.md b/locale/zh/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..a820b8df5 --- /dev/null +++ b/locale/zh/CODE_OF_CONDUCT.md @@ -0,0 +1,12 @@ +--- +title: Contributor Code of Conduct +--- + +As contributors and maintainers of this project, +we pledge to follow the [The Carpentries Code of Conduct][coc]. + +Instances of abusive, harassing, or otherwise unacceptable behavior +may be reported by following our [reporting guidelines][coc-reporting]. + +[coc-reporting]: https://docs.carpentries.org/topic_folders/policies/incident-reporting.html +[coc]: https://docs.carpentries.org/topic_folders/policies/code-of-conduct.html diff --git a/locale/zh/CONTRIBUTING.md b/locale/zh/CONTRIBUTING.md new file mode 100644 index 000000000..5dfea562d --- /dev/null +++ b/locale/zh/CONTRIBUTING.md @@ -0,0 +1,151 @@ +# Contributing + +[Software Carpentry][swc-site] and [Data Carpentry][dc-site] are open source projects, +and we welcome contributions of all kinds: +new lessons, +fixes to existing material, +bug reports, +and reviews of proposed changes are all welcome. + +## Contributor Agreement + +By contributing, +you agree that we may redistribute your work under [our license](LICENSE.md). +In exchange, +we will address your issues and/or assess your change proposal as promptly as we can, +and help you become a member of our community. +Everyone involved in [Software Carpentry][swc-site] and [Data Carpentry][dc-site] +agrees to abide by our [code of conduct](CONDUCT.md). + +## How to Contribute + +The easiest way to get started is to file an issue +to tell us about a spelling mistake, +some awkward wording, +or a factual error. +This is a good way to introduce yourself +and to meet some of our community members. + +1. If you do not have a [GitHub][github] account, + you can [send us comments by email][contact]. + However, + we will be able to respond more quickly if you use one of the other methods described below. + +2. If you have a [GitHub][github] account, + or are willing to [create one][github-join], + but do not know how to use Git, + you can report problems or suggest improvements by [creating an issue][issues]. + This allows us to assign the item to someone + and to respond to it in a threaded discussion. + +3. If you are comfortable with Git, + and would like to add or change material, + you can submit a pull request (PR). + Instructions for doing this are [included below](#using-github). + +## Where to Contribute + +1. If you wish to change this lesson, + please work in , + which can be viewed at . + +2. If you wish to change the example lesson, + please work in , + which documents the format of our lessons + and can be viewed at . + +3. If you wish to change the template used for workshop websites, + please work in . + The home page of that repository explains how to set up workshop websites, + while the extra pages in + provide more background on our design choices. + +4. If you wish to change CSS style files, tools, + or HTML boilerplate for lessons or workshops stored in `_includes` or `_layouts`, + please work in . + +## What to Contribute + +There are many ways to contribute, +from writing new exercises and improving existing ones +to updating or filling in the documentation +and submitting [bug reports][issues] +about things that don't work, aren't clear, or are missing. +If you are looking for ideas, +please see [the list of issues for this repository][issues], +or the issues for [Data Carpentry][dc-issues] +and [Software Carpentry][swc-issues] projects. + +Comments on issues and reviews of pull requests are just as welcome: +we are smarter together than we are on our own. +Reviews from novices and newcomers are particularly valuable: +it's easy for people who have been using these lessons for a while +to forget how impenetrable some of this material can be, +so fresh eyes are always welcome. + +## What _Not_ to Contribute + +Our lessons already contain more material than we can cover in a typical workshop, +so we are usually _not_ looking for more concepts or tools to add to them. +As a rule, +if you want to introduce a new idea, +you must (a) estimate how long it will take to teach +and (b) explain what you would take out to make room for it. +The first encourages contributors to be honest about requirements; +the second, to think hard about priorities. + +We are also not looking for exercises or other material that only run on one platform. +Our workshops typically contain a mixture of Windows, macOS, and Linux users; +in order to be usable, +our lessons must run equally well on all three. + +## Using GitHub + +If you choose to contribute via GitHub, +you may want to look at +[How to Contribute to an Open Source Project on GitHub][how-contribute]. +In brief: + +1. The published copy of the lesson is in the `gh-pages` branch of the repository + (so that GitHub will regenerate it automatically). + Please create all branches from that, + and merge the [master repository][repo]'s `gh-pages` branch into your `gh-pages` branch + before starting work. + Please do _not_ work directly in your `gh-pages` branch, + since that will make it difficult for you to work on other contributions. + +2. We use [GitHub flow][github-flow] to manage changes: + 1. Create a new branch in your desktop copy of this repository for each significant change. + 2. Commit the change in that branch. + 3. Push that branch to your fork of this repository on GitHub. + 4. Submit a pull request from that branch to the [master repository][repo]. + 5. If you receive feedback, + make changes on your desktop and push to your branch on GitHub: + the pull request will update automatically. + +Each lesson has two maintainers who review issues and pull requests +or encourage others to do so. +The maintainers are community volunteers, +and have final say over what gets merged into the lesson. + +## Other Resources + +General discussion of [Software Carpentry][swc-site] and [Data Carpentry][dc-site] +happens on the [discussion mailing list][discuss-list], +which everyone is welcome to join. +You can also [reach us by email][contact]. + +[contact]: mailto:admin@software-carpentry.org +[dc-issues]: https://github.com/issues?q=user%3Adatacarpentry +[dc-lessons]: http://datacarpentry.org/lessons/ +[dc-site]: http://datacarpentry.org/ +[discuss-list]: http://lists.software-carpentry.org/listinfo/discuss +[github]: http://github.com +[github-flow]: https://guides.github.com/introduction/flow/ +[github-join]: https://github.com/join +[how-contribute]: https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github +[issues]: https://github.com/swcarpentry/shell-novice/issues/ +[repo]: https://github.com/swcarpentry/shell-novice/ +[swc-issues]: https://github.com/issues?q=user%3Aswcarpentry +[swc-lessons]: http://software-carpentry.org/lessons/ +[swc-site]: http://software-carpentry.org/ diff --git a/locale/zh/LICENSE.md b/locale/zh/LICENSE.md new file mode 100644 index 000000000..696cc3ae1 --- /dev/null +++ b/locale/zh/LICENSE.md @@ -0,0 +1,82 @@ +--- +title: Licenses +--- + +## Instructional Material + +All Software Carpentry, Data Carpentry, and Library Carpentry instructional material is +made available under the [Creative Commons Attribution +license][cc-by-human]. The following is a human-readable summary of +(and not a substitute for) the [full legal text of the CC BY 4.0 +license][cc-by-legal]. + +You are free: + +- to **Share**---copy and redistribute the material in any medium or format +- to **Adapt**---remix, transform, and build upon the material + +for any purpose, even commercially. + +The licensor cannot revoke these freedoms as long as you follow the +license terms. + +Under the following terms: + +- **Attribution**---You must give appropriate credit (mentioning that + your work is derived from work that is Copyright © Software + Carpentry and, where practical, linking to + http\://software-carpentry.org/), provide a [link to the + license][cc-by-human], and indicate if changes were made. You may do + so in any reasonable manner, but not in any way that suggests the + licensor endorses you or your use. + +**No additional restrictions**---You may not apply legal terms or +technological measures that legally restrict others from doing +anything the license permits. With the understanding that: + +Notices: + +- You do not have to comply with the license for elements of the + material in the public domain or where your use is permitted by an + applicable exception or limitation. +- No warranties are given. The license may not give you all of the + permissions necessary for your intended use. For example, other + rights such as publicity, privacy, or moral rights may limit how you + use the material. + +## Software + +Except where otherwise noted, the example programs and other software +provided by Software Carpentry and Data Carpentry are made available under the +[OSI][osi]-approved +[MIT license][mit-license]. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +## Trademark + +"Software Carpentry" and "Data Carpentry" and their respective logos +are registered trademarks of [Community Initiatives][ci]. + +[cc-by-human]: https://creativecommons.org/licenses/by/4.0/ +[cc-by-legal]: https://creativecommons.org/licenses/by/4.0/legalcode +[mit-license]: https://opensource.org/licenses/mit-license.html +[ci]: http://communityin.org/ +[osi]: https://opensource.org diff --git a/locale/zh/README.md b/locale/zh/README.md new file mode 100644 index 000000000..fec09d0f3 --- /dev/null +++ b/locale/zh/README.md @@ -0,0 +1,75 @@ +# Introduction to genomic data analysis with R and Bioconductor + +[![Create a Slack Account with us](https://img.shields.io/badge/Create_Slack_Account-The_Carpentries-071159.svg)](https://swc-slack-invite.herokuapp.com/) + +## Contributing + +We welcome all contributions to improve the lesson! Maintainers will +do their best to help you if you have any questions, concerns, or +experience any difficulties along the way. + +We'd like to ask you to familiarize yourself with our Contribution +Guide and have a look at the [more detailed +guidelines][lesson-example] on proper formatting, ways to render the +lesson locally, and even how to write new episodes. + +Please see the current list of [issues][FIXME] for ideas for +contributing to this repository. For making your contribution, we use +the GitHub flow, which is nicely explained in the chapter +Contributing to a +Project +in Pro Git by Scott Chacon. + +Look for the tag +![good\_first\_issue](https://img.shields.io/badge/-good%20first%20issue-gold.svg). This +indicates that the maintainers will welcome a pull request fixing this +issue. + +## Useful links + +- If you're going to be developing lesson material for the first time + according to our design principles, consider reading the + [Carpentries Curriculum Development Handbook][cdh] +- Consult the [Lesson Example][lesson-example] website to find out more about + working with the lesson template + +## Lesson team + +This lesson has been developed and is current maintained by + +- Laurent Gatto (maintainer) +- Charlotte Soneson +- Jenny Drnevich +- Robert Castelo +- Kevin Rue-Albert + +We would also like to acknowledge the contributions of: + +- Oliver Crook, Sarah Kaspar, Nick Hirschmueller, Lisa Breckels and Maria Doyle for their contributions during the Bioconductor introduction workshop in Heidelberg, as part of EuroBioc2021 |> 2022. +- Axelle Loriot, Marco Chiapelle, Manon Martin and Toby Hodges for various contributions and discussions. +- lmsimp, alorot, manonmartin, mchiapello, stavares843, JennyZadeh, csdaw, ninja-1337, fursham-h, lagerratrobe, fmichonneau, federicomarini, tobyhodges for pull requests. + +If we have contributed but we missed you, apologies, and feel free to add yourself with a PR. + +## Authors + +A list of contributors to the lesson can be found in [AUTHORS](AUTHORS) + +## Citation + +To cite this lesson, please consult with [CITATION](CITATION) + +[lesson-example]: https://carpentries.github.io/lesson-example +[cdh]: https://cdh.carpentries.org + +## Testing locally + +To test locally, run the following in the lessons directory: + +```r +sandpaper::serve() +``` + +For more details, see the [workbench installation +instructions](https://carpentries.github.io/workbench/#installation]. + diff --git a/locale/zh/config.yaml b/locale/zh/config.yaml new file mode 100644 index 000000000..204cb59c5 --- /dev/null +++ b/locale/zh/config.yaml @@ -0,0 +1,61 @@ +#------------------------------------------------------------ +#Values for this lesson. +#------------------------------------------------------------ +#Which carpentry is this (swc, dc, lc, or cp)? +#swc: Software Carpentry +#dc: Data Carpentry +#lc: Library Carpentry +#cp: Carpentries (to use for instructor training for instance) +#incubator: The Carpentries Incubator +carpentry: 'incubator' +#Overall title for pages. +title: 'Introduction to data analysis with R and Bioconductor' +#Date the lesson was created (YYYY-MM-DD, this is empty by default) +created: '2020-09-14' +#Comma-separated list of keywords for the lesson +keywords: 'software, data, lesson, The Carpentries' +#Life cycle stage of the lesson +#possible values: pre-alpha, alpha, beta, stable +life_cycle: 'stable' +#License of the lesson +license: 'CC-BY 4.0' +#Link to the source repository for this lesson +source: 'https://github.com/carpentries-incubator/bioc-intro' +#Default branch of your lesson +branch: 'main' +#Who to contact if there are any issues +contact: 'laurent.gatto@uclouvain.be' +#Navigation ------------------------------------------------ +#Use the following menu items to specify the order of +#individual pages in each dropdown section. Leave blank to +#include all pages in the folder. +#Example ------------- +#episodes: +#- introduction.md +#- first-steps.md +#learners: +#- setup.md +#instructors: +#- instructor-notes.md +#profiles: +#- one-learner.md +#- another-learner.md +#Order of episodes in your lesson +episodes: + - 10-data-organisation.Rmd + - 20-r-rstudio.Rmd + - 23-starting-with-r.Rmd + - 25-starting-with-data.Rmd + - 30-dplyr.Rmd + - 40-visualization.Rmd + - 60-next-steps.Rmd +#Information for Learners +learners: +#Information for Instructors +instructors: +#Learner Profiles +profiles: +#Customisation --------------------------------------------- +#This space below is where custom yaml items (e.g. pinning +#sandpaper and varnish versions) should live +url: 'https://carpentries-incubator.github.io/bioc-intro' diff --git a/locale/zh/episodes/10-data-organisation.Rmd b/locale/zh/episodes/10-data-organisation.Rmd new file mode 100644 index 000000000..f956511ac --- /dev/null +++ b/locale/zh/episodes/10-data-organisation.Rmd @@ -0,0 +1,832 @@ +--- +source: Rmd +title: 使用电子表格组织数据 +teaching: 30 +exercises: 30 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- 了解电子表格及其优点和缺点。 +- 我们该如何在电子表格中格式化数据以有效使用数据? +- 了解常见的电子表格错误以及如何纠正它们。 +- 根据整洁数据原则组织您的数据。 +- 了解基于文本的电子表格格式,例如逗号分隔 (CSV) 或制表符分隔 (TSV) 格式。 + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- 如何组织表格数据? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +> 本集基于 Data Carpentries 的_面向生态学家的 R 语言数据分析和 +> 可视化_课程。 + +## 电子表格程序 + +**问题** + +- 使用电子表格进行良好的数据 + 组织的基本原则是什么? + +**客观的** + +- Describe best practices for organizing data so computers can make + the best use of datasets. + +**关键** + +- 良好的数据组织是任何研究项目的基础。 + +良好的数据组织是您的研究 +项目的基础。 大多数研究人员都有数据或在 +电子表格中输入数据。 电子表格程序是非常有用的图形 +界面,用于设计数据表和处理非常基本的数据 +质量控制功能。 另请参阅@Broman:2018。 + +### 电子表格大纲 + +电子表格适合数据输入。 因此,我们在电子表格中有大量数据 +。 作为研究人员,你的大部分时间将花在 +这个“数据整理”阶段。 这虽然不是最有趣的,但它是 +必要的。 我们将教您如何思考数据组织和 +一些更有效的数据整理实践。 + +### 这堂课不会教你什么 + +- 如何在电子表格中进行_统计_ +- 如何在电子表格中绘图 +- 如何在电子表格程序中“编写代码” + +如果你想这样做,一个很好的参考是 O'Reilly 出版的 Head First +Excel, +。 + +### 为什么我们不在电子表格中教授数据分析 + +- 电子表格中的数据分析通常需要大量的手动 + 工作。 如果您想更改参数或使用 + 新数据集运行分析,通常必须手动重做所有操作。 (我们确实 + 知道您可以创建宏,但请参阅下一点。) + +- 当您想要返回到 + 您的工作或有人询问您的分析细节时,追踪或重现电子表格程序中完成的统计或绘制 + 分析也很困难。 + +有许多电子表格程序可供使用。 由于大多数参与者 +使用 Excel 作为主要电子表格程序,本课将 +使用 Excel 示例。 A free spreadsheet program that can also +be used is LibreOffice. 程序之间的命令可能略有不同, +但总体思路是相同的。 + +Spreadsheet programs encompass a lot of the things we need to be able +to do as researchers. 我们可以用它们来做: + +- 数据输入 +- 组织数据 +- 数据子集和排序 +- 统计数据 +- 绘图 + +电子表格程序使用表格来表示和显示数据。 格式化为表格的数据 +也是本章的主题,我们 +将看到如何以标准化的方式将数据组织成表格,以 +确保高效的下游分析。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战:与邻居讨论以下几点 + +- 您在研究、课程、 + 或在家里使用过电子表格吗? +- 您在电子表格中进行哪些类型的操作? +- 您认为电子表格适合用于哪些方面? +- 您是否曾在电子表格程序中意外地做了一些令您 + 感到沮丧或悲伤的事情? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +### 电子表格问题 + +电子表格适合于数据输入,但实际上我们倾向于 +使用电子表格程序进行更多数据输入以外的用途。 我们使用它们 +来创建出版物的数据表,生成摘要 +统计数据,并制作图表。 + +在电子表格中生成用于出版的表格并不是 +最佳选择——通常,在格式化用于出版的数据表时,我们 +以一种实际上并不打算 +被读取为数据的方式报告关键汇总统计数据,并且通常涉及特殊格式 +(合并单元格、创建边框、使其美观)。 我们建议您 +在文档编辑软件中执行此类操作。 + +The latter two applications, generating statistics and figures, should +be used with caution: because of the graphical, drag and drop nature of +spreadsheet programs, it can be very difficult, if not impossible, to +replicate your steps (much less retrace anyone else's), particularly if your +stats or figures require you to do more complex calculations. Furthermore, +in doing calculations in a spreadsheet, it's easy to accidentally apply a +slightly different formula to multiple adjacent cells. 当使用基于 +命令行的统计程序(例如 R 或 SAS)时,除非您有意为之,否则几乎不可能 +将计算应用于 +数据集中的一个观察结果,而不应用于另一个观察结果。 + +### 使用电子表格进行数据输入和清理 + +在本课中,我们假设您很可能使用 Excel 作为 +您主要的电子表格程序 - 还有其他程序(gnumeric、OpenOffice 的 Calc +),它们的功能类似,但 Excel 似乎 +是生物学家和生物医学研究人员最常用的程序。 + +在本课中我们将讨论: + +1. 格式化电子表格中的数据表 +2. 格式问题 +3. 导出数据 + +## 格式化电子表格中的数据表 + +**问题** + +- 我们该如何在电子表格中格式化数据以有效使用数据? + +**目标** + +- 描述在 + 电子表格中输入和格式化数据的最佳实践。 + +- 应用最佳实践在 + 电子表格中排列变量和观察结果。 + +**关键点** + +- 切勿修改原始数据。 在进行任何 + 更改之前,务必先进行复制。 + +- 在 + 纯文本文件中跟踪您清理数据所采取的所有步骤。 + +- 根据整洁数据原则组织您的数据。 + +最常见的错误是将电子表格程序视为实验室 +笔记本,即依赖上下文、边缘注释、数据和字段的空间 +布局来传达信息。 作为人类,我们可以 +(通常)解释这些事物,但计算机不会以相同的方式查看信息 +,并且除非我们向计算机解释每个 +事物的含义(这可能很难!),否则它将无法看到 +我们的数据是如何组合在一起的。 + +Using the power of computers, we can manage and analyse data in much +more effective and faster ways, but to use that power, we have to set +up our data for the computer to be able to understand it (and +computers are very literal). + +这就是为什么从一开始就设置格式良好的表格 +非常重要 - 甚至在您开始输入您的 +第一次初步实验的数据之前。 数据组织是 +研究项目的基础。 它可以使您在整个分析过程中处理 +数据变得更容易或更难,因此在 +进行数据输入或设置实验时值得考虑。 您可以在电子表格中以不同的方式进行 +设置,但其中一些 +选择可能会限制您处理其他程序中数据的能力 +,或者限制 6 个月后的您或您的合作者处理 +数据。 + +\*\*注意:\*\*数据输入和数据分析的最佳布局/格式(以及软件和 +界面)可能不同。 It is +important to take this into account, and ideally automate the +conversion from one to another. + +### 跟踪你的分析 + +当您使用电子表格时,在数据清理或 +分析期间,很容易得到与您开始时非常 +不同的电子表格。 为了能够 +重现你的分析,或者在审稿人或 +导师要求进行不同的分析时弄清楚你做了什么,你应该 + +- 使用您清理或分析过的数据创建一个新文件。 不要修改 + 原始数据集,否则您将永远不知道从哪里开始! + +- 跟踪您在清理或分析中所采取的步骤。 您 + 应该像追踪实验中的任何步骤一样追踪这些步骤。 我们 + 建议您在与数据文件存储在同一个 + 文件夹中的纯文本文件中执行此操作。 + +这可能是电子表格设置的一个示例: + +![](图/电子表格设置更新.png) + +今天在练习中将这些原则付诸实践。 + +虽然版本控制超出了本课程的范围,但您可以查看 +Carpentries 课程中关于 +['Git'](https://swcarpentry.github.io/git-novice/) 的内容,了解如何 +对数据进行**版本控制**。 另请参阅此 博客 +帖子 了解快速教程或 +@Perez-Riverol:2016 了解更面向研究的用例。 + +### 在电子表格中构建数据 + +使用电子表格程序处理数据的基本规则: + +1. 将所有变量放在列中 - 您要测量的东西, + 例如“重量”或“温度”。 +2. 将每个观察结果放在其自己的行中。 +3. 不要在一个单元格中合并多条信息。 有时 + 看起来只是一件事,但想想如果这是唯一的方法 + 你会希望能够使用或排序这些数据。 +4. 保留原始数据 - 不要更改它! +5. 将清理后的数据导出为基于文本的格式,如 CSV + (逗号分隔值)格式。 这确保任何人都可以使用 + 数据,并且是大多数数据存储库所要求的。 + +例如,我们拥有来自比利时布鲁塞尔几家 +家医院的患者的数据。 They recorded the date of the visit, +the hospital, the patients' gender, weight and blood group. + +如果我们像这样跟踪数据: + +![](图/multiple-info.png) + +问题在于 ABO 和 Rh 血型位于同一个“血液” +类型列中。 因此,如果他们想要查看 A +组的所有观察结果或查看 ABO 组的体重分布,使用此数据设置执行此操作会很棘手 +。 如果我们将 ABO 和 Rh 血型 +组放在不同的列中,您会发现这会容易得多。 + +![](图/单个信息.png) + +设置数据表时的一个重要规则是**列 +用于变量**并且**行用于观察**: + +- 列是变量 +- 行是观察值 +- 单元格是单独的值 + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战:我们将获取一个混乱的数据集并描述如何清理它。 + +1. 点击 + [此处](https://github.com/UCLouvain-CBIO/WSBIM1207/raw/master/data/messy_covid.xlsx) 下载混乱的数据集。 + +2. 在电子表格程序中打开数据。 + +3. 您可以看到有两个选项卡。 The data contains various + clinical variables recorded in various hospitals in Brussels during + the first and second COVID-19 waves in 2020. 如您所见,在 3 月和 11 月的 + 波期间, + 数据的记录方式有所不同。 现在您是该项目的负责人,并且您希望 + 能够开始分析数据。 + +4. 与您旁边的人一起,找出这个 + 电子表格中存在的问题。 还要讨论清理 + 第一和第二波标签所需采取的步骤,并将它们全部放在一个 + 电子表格中。 + +\*\*重要:\*\*不要忘记我们的第一条建议:为清理后的数据创建一个 +新文件(或选项卡),切勿修改原始 +(原始)数据。 + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +After you go through this exercise, we'll discuss as a group what was +wrong with this data and how you would fix it. + + + + + + + + + + + + + + + + + + + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战:整理好数据后,回答以下问题: + +- 有多少男性和女性参加了这项研究? +- 已检测出 A 型、AB 型、B 型各有多少个? +- 如上所述,但忽略受污染的样本? +- 已检测了多少 Rh 阳性和 Rh 阴性患者? +- 有多少位通用捐献者(O-)接受了检测? +- AB型男人的平均体重是多少? +- 不同医院检测了多少样本? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +一个**优秀的参考资料**,特别是关于 R 脚本 +的是_Tidy Data_ 论文@Wickham:2014。 + +## 常见的电子表格错误 + +**问题** + +- 在电子表格中格式化数据时会遇到哪些常见挑战? + 我们如何避免它们? + +**目标** + +- 识别并解决常见的电子表格格式问题。 + +**关键点** + +- 避免在一个电子表格中使用多个表格。 +- 避免将数据分散到多个选项卡中。 +- 将零记录为零。 +- 使用适当的空值来记录缺失的数据。 +- 不要使用格式来传达信息或让你的电子表格看起来漂亮。 +- 将评论放在单独的栏中。 +- 在列标题中记录单位。 +- 每个单元格中仅包含一条信息。 +- 避免在列标题中使用空格、数字和特殊字符。 +- 避免在数据中包含特殊字符。 +- 在单独的纯文本文件中记录元数据。 + + + + + + + + + +在您自己的 +数据以及来自合作者或互联网的数据中,有一些潜在的错误需要注意。 如果您 +意识到错误以及对下游 +数据分析和结果解释可能产生的负面影响,它可能会激励您自己 +和您的项目成员尝试避免这些错误。 对电子表格中数据格式的方式进行一些小的改变 +,可以在数据清理 +和分析时对效率和可靠性产生很大的 +影响。 + +- [使用多个表格](#tables) +- [使用多个标签](#tabs) +- [不填零](#zeros) +- [使用有问题的空值](#null) +- [使用格式传达信息](#formatting) +- [使用格式让数据表看起来更美观](#formatting_pretty) +- [在单元格中放置注释或单位](#units) +- [在一个单元格中输入多条信息](#info) +- [使用有问题的字段名称](#field_name) +- [在数据中使用特殊字符](#special) +- [在数据表中包含元数据](#metadata) + +### 使用多个表 {#tables} + +一种常见的策略是在一个 +电子表格内创建多个数据表。 这会让计算机感到困惑,所以不要这样做! 当您 +在一个电子表格中创建多个表格时,您会在计算机中绘制事物之间的错误 +关联,计算机会将每一行视为 +一个观察结果。 您还可能会在 +多个地方使用相同的字段名称,这将使您更难将数据清理为 +可用形式。 下面的例子描述了这个问题: + +![](图/2_数据表_示例.jpg) + +在上面的例子中,计算机将看到(例如)第 4 行和 +假设所有 A-AF 列都指的是同一个样本。 此行 +实际上代表四个不同的样本(四个 +不同收集日期中的每个日期都有一个样本 1 - 5 月 29 日、6 月 12 日、6 月 19 日和 6 月 +26 日),以及一些计算出的汇总统计数据(平均值 (avr) +和标准测量误差 (SEM))对于其中两个 +样本。 其他行也存在类似问题。 + +### 使用多个标签 {#tabs} + +但是工作簿标签怎么办? 这似乎是组织 +数据的一种简单方法,对吗? 嗯,是也不是。 当您创建额外的选项卡时,您无法 +允许计算机查看数据中的连接(您 +必须引入电子表格应用程序特定的函数或 +脚本来确保这种连接)。 举例来说,你为每天进行的测量创建一个 +单独的标签。 + +这不是一个好的做法,原因有二: + +1. 如果你每次测量时都在新标签页中开始记录数据 + ,那么你很可能会意外地在你的 + 数据中添加不一致的内容,并且 + +2. 即使你设法防止所有不一致性出现, + 你也需要在分析数据 + 之前为自己添加一个额外的步骤,因为你必须将这些数据合并到单个 + 数据表中。 您必须明确地告诉计算机如何 + 组合标签 - 如果标签格式不一致,您 + 甚至可能必须手动执行此操作。 + +下次输入数据并创建另一个选项卡 +或表格时,问问自己是否可以通过在原始电子表格中添加 +另一列来避免添加此选项卡。 在 +混乱数据文件示例中,我们使用了多个选项卡,但现在您已经了解了如何 +重新组织数据以跨选项卡合并。 + +在 +实验过程中,您的数据表可能会变得很长。 如果您在电子表格顶部看不到 +标题,这将使输入数据变得更加困难。 但不要重复你的标题 +行。 这些很容易混入数据中,从而导致以后出现问题 +。 相反,您可以冻结列 +标题 +,这样即使您的电子表格包含许多 +行,它们仍然可见。 + +### 不填零 {#zeros} + +当您测量某个东西时,它通常为零, +表示在调查中观察到兔子的次数。 既然该列大部分都是零,为什么还要费心 +在该列中写入数字零? + +但是,在 +电子表格中,零和空白单元格之间存在差异。 对于计算机来说,零实际上是数据。 您测量了或者 +计算了它。 空白单元格表示未经测量,并且 +计算机将其解释为未知值(也称为空 +或缺失值)。 + +电子表格或统计程序可能会误解您希望为零的 +空白单元格。 通过不输入观察值 +,您就是在告诉计算机将数据 +表示为未知或缺失(空)。 这可能会导致后续 +计算或分析出现问题。 例如,包含单个空值的一组数字 +的平均值始终为空(因为 +计算机无法猜测缺失观测值的值)。 由于 +这个原因,将零记录为零以及将真正 +缺失数据记录为空值非常重要。 + +### 使用有问题的空值 {#null} + +**示例**:使用 -999 或其他数值(或零)至 +表示缺失数据。 + +**解决方案**: + +有几个原因导致数据集中的空值以不同方式表示 +。 有时,测量设备会自动记录令人困惑的空值 +。 If that's the case, there's not +much you can do, but it can be addressed in data cleaning with a tool +like +[OpenRefine](https://www.datacarpentry.org/OpenRefine-ecology-lesson/) +before analysis. 其他时候,不同的空值用于传达 +数据不存在的不同原因。 这是需要捕获的重要 +信息,但实际上是使用一列来捕获 +两条信息。 就像 使用格式来传达 +信息 一样,在这里创建一个新的 +列(如 'data\_missing')并使用该列来捕获 +不同的原因会很好。 + +无论原因是什么,如果未知或缺失的数据 +记录为 -999、999 或 0,那就有问题了。 + +许多统计程序不会认识到这些旨在用 +来表示缺失(空)值。 如何解释这些值 +将取决于您用来分析数据的软件。 It is +essential to use a clearly defined and consistent null indicator. + +空白(大多数应用)和 NA(对于 R)是良好的 +选择。 @White:2013 在他们的文章中解释了为不同的软件应用程序指示空值 +的良好选择: + +![](图/3_white_table_1.jpg) + +### 使用格式传达信息 {#formatting} + +**示例**:突出显示应从分析中排除的 +单元格、行或列,留下空白行以指示数据中的 +分离。 + +![](图/格式化.png) + +**解决方案**:创建一个新字段来编码哪些数据应该被 +排除。 + +![](图/good_formatting.png) + +### 使用格式化使数据表看起来更漂亮{#formatting\_pretty} + +**示例**:合并单元格。 + +**解决方案**:如果您不小心,将工作表格式化为更美观的 +可能会影响您的计算机查看数据中的 +关联的能力。 合并的单元格将导致统计软件无法读取您的数据 +。 考虑以这样的方式重构您的数据 +,这样您就不需要合并单元格来组织您的数据。 + +### 将注释或单元放置在单元格中 {#units} + +大多数分析软件无法看到 Excel 或 LibreOffice 注释,并且 +会对数据单元内的注释感到困惑。 正如 +上面描述的格式化一样,如果您需要 +向单元格添加注释,请创建另一个字段。 类似地,不要在单元格中包含单位:理想情况下, +放在一列中的所有测量值都应该在同一个 +单位中,但如果由于某种原因它们不在,请创建另一个字段并 +指定单元格所在的单位。 + +### 在一个单元格中输入多条信息 {#info} + +**示例**:在一个单元格中记录 ABO 和 Rh 血型,例如 A+、 +B+、A-、... + +**解决方案**:不要在 +单元格中包含多条信息。 这将限制您分析数据的方式。 如果 +您需要这两种测量值,请设计您的数据表以包含 +此信息。 For example, include one column for the ABO group and +one for the Rhesus group. + +### 使用有问题的字段名称 {#field\_name} + +选择描述性的字段名称,但注意不要包含空格、 +数字或任何类型的特殊字符。 使用空格作为分隔符的解析器可能会误解空格 +,并且某些 +程序不喜欢以 +数字开头的文本字符串作为字段名称。 + +下划线(`_`)是空格的良好替代品。 考虑以驼峰式命名法书写 +名称(像这样:ExampleFileName)以提高 +的可读性。 请记住,目前有意义的缩写 +可能在 6 个月后就不那么明显了,但不要使用过长的名称 +。 在字段名称中包含单位可避免 +混淆,并使其他人能够轻松解释您的字段。 + +**例子** + +| 好名字 | 不错的选择 | 避免 | +| ----------------------------- | ----- | ---------------------------- | +| 最高温度 | 最高温度 | 最高温度 (°C) | +| 降水量\_mm | 沉淀 | 预CMM | +| 平均年增长率 | 年均增长率 | 平均年增长率 | +| 性别 | 性别 | 男/女 | +| 重量 | 重量 | w. | +| 单元格类型 | 单元格类型 | 单元格类型 | +| 观察\_01 | 第一次观察 | 第一次观察 | + +### 在数据中使用特殊字符 {#special} + +**示例**:在写笔记时,您将电子表格程序视为文字处理器 +,例如直接从 Word 或 +其他应用程序复制数据。 + +**解决方案**:这是一种常见的策略。 例如,当在单元格中写入 +较长的文本时,人们通常会在电子表格中包含换行符、破折号、 +等。 另外,从 +应用程序(例如 Word)复制数据时,格式和花哨的非标准 +字符(例如左对齐和右对齐的引号)将包含在 +中。 将这些数据导出到编码/统计 +环境或关系数据库时,可能会发生危险的事情, +例如行被切成两半,并出现编码错误。 + +一般的最佳做法是避免添加换行符、 +制表符和垂直制表符等字符。 换句话说,将文本单元格视为 +一个只能包含文本和空格的简单 Web 表单。 + +### 在数据表中包含元数据 {#metadata} + +**示例**:在数据表的顶部或底部添加图例 +,解释列的含义、单位、例外等。 + +**解决方案**:记录有关您的数据的数据(“元数据”)是 +至关重要。 在 +收集和分析数据集时,您可能对数据集了如指掌,但几个月、一年或更长时间后,您仍然 +记得变量“sglmemgp”表示组中的单个成员,例如 +,或者您用来转换变量 +或创建派生变量的确切算法的可能性很小。 + +同样,其他人可能出于多种原因想要检查或 +使用您的数据 - 了解您的发现、验证您的发现、 +审查您提交的出版物、复制您的结果、 +设计类似的研究,甚至存档您的数据以供他人访问和 +重复使用。 虽然数字数据从定义上来说是 +机器可读的,但理解其含义却是人类 +的工作。 在研究的收集 +和分析阶段记录数据的重要性怎么强调也不为过, +尤其是当您的研究将成为学术 +记录的一部分时。 + +但是,元数据不应该包含在数据文件 +本身中。 与论文或补充文件中的表格不同,元数据(以 +图例的形式)不应包含在数据文件中,因为此 +信息不是数据,并且包含它可能会破坏计算机 +程序对数据文件的解释方式。 相反,元数据应该作为单独的文件存储在 +与数据文件位于同一目录中,最好以纯文本格式存储在 +中,并且其名称应与 +数据文件明确关联。 Because metadata files are free text format, they also +allow you to encode comments, units, information about how null values +are encoded, etc. that are important to document but can disrupt the +formatting of your data file. + +此外,文件或数据库级别的元数据描述了组成数据集的 +文件彼此间的关系、它们的格式是什么;以及 +它们是否取代了以前的文件或者被以前的文件取代。 +文件夹级别的 readme.txt 文件是记录项目中所有 +文件和文件夹的经典方式。 + +(Text on metadata adapted from the online course Research Data +[MANTRA](https://datalib.edina.ac.uk/mantra) by EDINA and Data Library, +University of Edinburgh. MANTRA 已获得 Creative Commons +Attribution 4.0 International +License 的许可。) + +## 导出数据 + +**问题** + +- 我们如何才能以对 + 下游应用程序有用的方式从电子表格中导出数据? + +**目标** + +- 以通用文件格式存储电子表格数据。 +- 将数据从电子表格导出到 CSV 文件。 + +**关键点** + +- Data stored in common spreadsheet formats will often not be read + correctly into data analysis software, introducing errors into your + data. + +- 将数据从电子表格导出为 CSV 或 TSV 等格式,会将其 + 置于大多数程序可以一致使用的格式中。 + +将您要用于分析的数据存储在 Excel +默认文件格式(`*.xls` 或 `*.xlsx` - 取决于 Excel +版本)中并不是一个好主意。 为什么? + +- 因为它是一种专有格式,并且有可能在 + 未来,技术将不再存在(或者变得足够稀有),从而导致 + 打开文件变得不方便,甚至不可能。 + +- 其他电子表格软件可能无法打开以 + 专有 Excel 格式保存的文件。 + +- 不同版本的 Excel 可能以不同的方式处理数据,导致 + 不一致。 [日期](https://datacarpentry.org/spreadsheet-ecology-lesson/03-dates-as-data/index.html) + 是数据存储不一致的一个有据可查的例子。 + +- Finally, more journals and grant agencies are requiring you to + deposit your data in a data repository, and most of them don't + accept Excel format. 它需要采用下面讨论的 + 格式之一。 + +- 上述要点也适用于其他格式,例如 LibreOffice / Open Office 使用的开放数据 + 格式。 这些格式不是 + 静态的,并且不会被不同的软件 + 包以相同的方式解析。 + +Storing data in a universal, open, and static format will help deal +with this problem. 尝试制表符分隔(制表符分隔值或 TSV)或 +逗号分隔(逗号分隔值或 CSV)。 CSV 文件是普通的 +文本文件,其中列由逗号分隔,因此为“逗号 +分隔值”或 CSV。 CSV 文件相对于 +Excel/SPSS/等文件的优势在于,我们可以使用 +几乎任何软件打开和读取 CSV 文件,包括纯文本编辑器,如 TextEdit 或 +NotePad。 CSV 文件中的数据还可以轻松导入到其他 +格式和环境中,例如 SQLite 和 R。当我们使用 CSV +文件时,我们不受 +某个昂贵程序的某个版本的限制,因此它是一种很好的格式,可以实现最大的可移植性和 +耐用性。 Most spreadsheet programs can save to delimited text +formats like CSV easily, although they may give you a warning during +the file export. + +要以 CSV 格式保存在 Excel 中打开的文件: + +1. 从顶部菜单中选择“文件”和“另存为”。 +2. 在“格式”字段中,从列表中选择“以逗号分隔的 + 值”(`*.csv`)。 +3. 仔细检查文件名和要保存的位置 + 然后点击“保存”。 + +关于向后兼容性的重要说明:您可以在 Excel 中打开 CSV 文件 +! + +```{r, results="markup", fig.cap="Saving an Excel file to CSV.", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/excel-to-csv.png") +``` + +**关于 R 和 `xls`** 的注释:有一些 R 包可以读取 `xls` +文件(以及 Google 电子表格)。 甚至可以访问 `xls` 文档中的 +个不同的工作表。 + +**但** + +- 其中一些仅适用于 Windows。 +- 这相当于用数据分析 R 代码中的 + 额外的复杂性/依赖性替换 (简单但手动的) 导出到 `csv`。 +- 数据格式的最佳实践仍然适用。 +- 真的有充分的理由说明为什么 `csv`(或类似的东西)不适合 + 吗? + +### 关于逗号的注意事项 + +在某些数据集中,数据值本身可能包含逗号 +(,)。 In that case, the software which you use (including Excel) will +most likely incorrectly display the data in columns. 这是因为 +作为数据值一部分的逗号将被解释为 +分隔符。 + +例如,我们的数据可能如下所示: + +``` +species_id,genus,species,taxa +AB,Amphispiza,bilineata,Bird +AH,Ammospermophilus,harrisi,Rodent, not censused +AS,Ammodramus,savannarum,Bird +BA,Baiomys,taylori,Rodent +``` + +在记录“AH,Ammospermophilus,harrisi,Rodent, not censused”中,“taxa”的 +值包含逗号(“Rodent, not censused”)。 如果我们尝试 +将上述内容读入 Excel(或其他电子表格程序),我们将 +得到如下内容: + +```{r, results="markup", fig.cap="The risks of having commas inside comma-separated data.", echo=FALSE, purl=FALSE, out.width="80%", fig.align="center"} +knitr::include_graphics("fig/csv-mistake.png") +``` + +“taxa” 的值被分成两列(而不是被放在“D”列中的 +)。 这可能会导致更多 +错误。 例如,额外的列将被解释为具有许多缺失值(并且没有适当的标题)的列 +。 除 +之外,第 3 行记录的 `D` 列中的值(因此 +其中 'taxa' 的值包含逗号)现在不正确。 + +如果您想以 `csv` 格式存储数据,并预计 +数据值可能包含逗号,则可以通过将值放在引号(“”)中来避免上面讨论的 +问题。 应用此规则,我们的 +数据可能如下所示: + +``` +species_id,genus,species,taxa +"AB","Amphispiza","bilineata","Bird" +"AH","Ammospermophilus","harrisi","Rodent, not censused" +"AS","Ammodramus","savannarum","Bird" +"BA","Baiomys","taylori","Rodent" +``` + +现在在 Excel 中将此文件作为 `csv` 打开不会导致出现多余的 +列,因为 Excel 只会使用超出 +引号的逗号作为分隔字符。 + +Alternatively, if you are working with data that contains commas, you +likely will need to use another delimiter when working in a +spreadsheet[^decsep]. 在这种情况下,请考虑使用制表符作为分隔符,并使用 +来处理 TSV 文件。 TSV 文件可以以与 CSV 文件相同的方式从电子表格 +程序中导出。 + +[^decsep]: 这在欧洲 + 国家尤其重要,这些国家使用逗号作为小数 + 分隔符。 在这种情况下, + csv 文件中的默认值分隔符将是分号 (;),或者值将是 + 系统引用。 + +如果您正在处理一个已经存在的数据集,其中数据 +值未包含在“”中,但其中逗号既作为分隔符 +又作为数据值的一部分,则您可能会面临数据清理的一个主要问题 +。 如果您处理的数据集包含 +数百或数千条记录,手动清理它们(通过 +从数据值中删除逗号或将值放入 +引号中 - “”)不仅会花费数小时,而且可能 +最终导致您意外引入许多错误。 + +清理数据集是许多科学 +学科的主要问题之一。 该方法几乎总是依赖于特定的 +环境。 但是,以 +自动化的方式清理数据是一种很好的做法,例如通过编写和运行脚本。 +Python 和 R 课程将为您提供开发 +构建相关脚本的技能的基础。 + +## 概括 + +```{r analysis, results="asis", fig.margin=TRUE, fig.cap="A typical data analysis workflow.", fig.width=7, fig.height=4, echo=FALSE, purl=FALSE} +knitr::include_graphics("fig/analysis.png") +``` + +上图展示了典型的数据分析工作流程, +其中数据被重复转换、可视化和建模。 这个 +迭代重复多次,直到数据被理解。 然而,在 +许多现实生活中,大部分时间都花在清理和 +准备数据上,而不是实际分析和理解 +数据上。 + +敏捷的数据分析工作流程(包含 +转换/可视化/模型循环的几次快速迭代)只有在数据 +以可预测的方式格式化,并且可以推断数据 +而不必查看和/或修复它时才可行。 + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- 良好的数据组织是任何研究项目的基础。 + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/zh/episodes/20-r-rstudio.Rmd b/locale/zh/episodes/20-r-rstudio.Rmd new file mode 100644 index 000000000..0e8f73a6c --- /dev/null +++ b/locale/zh/episodes/20-r-rstudio.Rmd @@ -0,0 +1,667 @@ +--- +source: Rmd +title: R 和 RStudio +teaching: 30 +exercises: 0 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- 描述 RStudio 脚本、控制台、环境和绘图窗格的用途。 +- 将一组分析的文件和目录组织为 R 项目,并了解工作目录的用途。 +- 使用内置的 RStudio 帮助界面搜索有关 R 函数的更多信息。 +- 演示如何向 R 用户社区提供足够的信息以进行故障排除。 + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- 什么是 R 和 RStudio? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +> 本集基于 Data Carpentries 的_面向生态学家的 R 语言数据分析和 +> 可视化_课程。 + +## 什么是 R? 什么是 RStudio? + +术语 [R](https://www.r-project.org/) 用于指代 +_编程语言_、_统计计算环境_ +和 _解释使用该语言编写的脚本的软件_。 + +[RStudio](https://rstudio.com) 目前是一种非常流行的方式,不仅可以 +编写 R 脚本,还可以与 R +软件进行交互[^plainr]。 为了正常运行,RStudio 需要 R 和 +,因此两者都需要安装在您的计算机上。 + +[^plainr]: 与直接从命令行 + 控制台使用 R 相反。 还有其他软件可以将 + 与 R 进行接口和集成,但 RStudio 特别适合初学者 + ,同时提供许多非常高级的功能。 + +The RStudio IDE Cheat +Sheet +provides much more information than will be covered here, but can be +useful to learn keyboard shortcuts and discover new features. + +## 为什么要学习 R? + +### R 不需要大量的指向和点击,这是一件好事 + +学习曲线可能比其他软件更陡峭,但使用 +R,您的分析结果并不依赖于记住 +连续的指向和单击,而是依赖于一系列 +书面命令,这是一件好事! 因此,如果您因为收集了更多数据而想要重新进行 +分析,您不必 +记住您以何种顺序单击了哪个按钮来获得 +结果;您只需再次运行脚本即可。 + +使用脚本可以使您在分析中使用的步骤更加清晰, +并且您编写的代码可以由其他人检查,他们可以为您提供 +反馈并发现错误。 + +Working with scripts forces you to have a deeper understanding of what +you are doing, and facilitates your learning and comprehension of the +methods you use. + +### R 代码具有很好的可重复性 + +Reproducibility means that someone else (including your future self) can +obtain the same results from the same dataset when using the same +analysis code. + +R 与其他工具集成,从您的 +代码生成手稿或报告。 如果您收集了更多数据,或者修复了数据集中的错误,则手稿或报告中的 +图表和统计测试将自动更新 +。 + +越来越多的期刊和资助机构希望分析 +具有可重复性,因此了解 R 将使您在满足这些 +要求方面更具优势。 + +### R 是跨学科且可扩展的 + +R 有超过 10000 个软件包[^whatarepkgs]可供安装以扩展其 +功能,它提供了一个框架,允许您结合来自许多科学学科的 +统计方法,以最适合 +分析数据所需的分析框架。 例如, +R 具有用于图像分析、GIS、时间序列、人口 +遗传学等的软件包。 + +[^whatarepkgs]: 即赋予 R 新功能的附加组件, + 例如生物信息学数据分析。 + +```{r, fig.cap="Exponential increase of the number of packages available on [CRAN](https://cran.r-project.org/), the Comprehensive R Archive Network. From the R Journal, Volume 10/2, December 2018.", echo=FALSE, message=FALSE} +knitr::include_graphics("fig/cran.png") +``` + +### R 可处理各种形状和大小的数据 + +您通过 R 学到的技能会随着您的 +数据集的大小而轻松扩展。 无论您的数据集有数百行还是数百万行, +对您来说都不会有太大区别。 + +R 是为数据分析而设计的。 它带有特殊的数据结构 +和数据类型,可以方便地处理缺失数据和统计 +因素。 + +R 可以连接到您的计算机或网络上的电子表格、数据库和许多其他数据格式, +。 + +### R 生成高质量图形 + +R 中的绘图功能非常广泛,允许您调整 +图形的任何方面,以最有效地传达来自 +数据的信息。 + +### R 有一个庞大而热情的社区 + +每天都有成千上万的人使用 R。 他们中的许多人都愿意通过邮件列表和网站(例如 Stack +Overflow 或 RStudio +社区 为您提供帮助 +。 这些广泛的用户社区 +扩展到生物信息学等专业领域。 R 社区的一个这样的子集是 [Bioconductor](https://bioconductor.org/),这是一个用于分析和理解“来自当前和新兴生物检测的数据”的科学项目。 该研讨会由 Bioconductor 社区成员开发;有关 Bioconductor 的更多信息,请参阅配套研讨会 [“Bioconductor 项目”](https://carpentries-incubator.github.io/bioc-project/)。 + +### R 不仅免费,而且开源且跨平台 + +任何人都可以检查源代码来了解 R 的工作原理。 由于这种 +透明度,出现错误的可能性较小,如果您(或 +其他人)发现一些错误,您可以报告并修复错误。 + +## 了解 RStudio + +让我们首先了解 [RStudio](https://www.rstudio.com/), +它是一个用于处理 +R 的集成开发环境 (IDE)。 + +RStudio IDE 开源产品在 Affero General +Public License (AGPL) v3 下免费使用。 +RStudio IDE 还提供商业许可和 Posit, Inc. 的 +优先电子邮件支持。 + +我们将使用 RStudio IDE 编写代码,浏览我们 +计算机上的文件,检查我们要创建的变量,并可视化 +我们将生成的图表。 RStudio 还可用于其他事项 +(例如版本控制、开发包、编写 Shiny 应用程序),而 +我们不会在研讨会期间介绍这些事项。 + +```{r, results="markup", fig.cap="RStudio interface screenshot. Clockwise from top left: Source, Environment/History, Files/Plots/Packages/Help/Viewer, Console.", echo=FALSE, purl=FALSE, out.width="100%", fig.align="center"} +knitr::include_graphics("fig/rstudio-screenshot.png") +``` + +RStudio 窗口分为 4 个“窗格”: + +- 脚本和文档的**来源**(左上角,在 + 默认布局中) +- 你的**环境/历史**(右上), +- 您的 **Files/Plots/Packages/Help/Viewer** (右下角),以及 +- R **控制台**(左下)。 + +这些窗格的位置和它们的内容可以自定义(参见 +菜单,“工具->全局选项->窗格布局”)。 + +One of the advantages of using RStudio is that all the information you +need to write code is available in a single window. 此外,通过 +的许多快捷方式、**自动完成**和**突出显示**,针对您在 R 中开发时使用的主要 +文件类型,RStudio 将使输入 +变得更容易且更不容易出错。 + +## 开始设置 + +将一组相关数据、分析和文本 +保存在一个文件夹中,称为 **工作 +目录**,是一种很好的做法。 然后,此文件夹中的所有脚本都可以使用 +**相对路径** 来指示 +文件在项目内部的位置(而不是绝对路径,绝对路径指向 +文件在特定计算机上的位置)。 Working this way makes it a lot +easier to move your project around on your computer and share it with +others without worrying about whether or not the underlying scripts +will still work. + +RStudio 通过其“项目” +界面提供了一套有用的工具来执行此操作,它不仅可以为您创建工作目录,还可以记住 +它的位置(允许您快速导航到它)并可选择保留 +自定义设置和打开的文件,以便在 +休息后更容易恢复工作。 按照下面为本 +教程创建“R 项目”的步骤进行操作。 + +1. 启动 RStudio。 +2. 在“文件”菜单下,点击“新建项目”。 选择“新目录”,然后 + “新项目”。 +3. 输入这个新文件夹(或“目录”)的名称,并为其选择一个 + 方便的位置。 这将是您本次会话(或整个课程)的**工作目录** + (例如`bioc-intro`)。 +4. 点击“创建项目”。 +5. (可选)将首选项设置为“从不”在 RStudio 中保存工作区。 + +RStudio 的默认首选项通常运行良好,但将工作区保存到 +.RData 可能会很麻烦,特别是在处理较大的数据集时。 +要关闭该功能,请转到工具-->“全局选项”,然后在退出时选择“从不”选项 +以将“工作区保存到.RData”。 + +```{r, results="markup", fig.cap="Set 'Save workspace to .RData on exit' to 'Never'", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/rstudio-preferences.png") +``` + +为了避免 Windows 与其他操作系统 +之间的字符编码问题,我们 +将默认设置 UTF-8: + +```{r, results="markup", fig.cap="Set the default text encoding to UTF-8 to save us headache in the coming future. (Figure from the link above).", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/utf8.png") +``` + +### 组织你的工作目录 + +在您的项目中使用一致的文件夹结构将有助于保持事物 +井然有序,并且还能让您在将来轻松查找/归档事物。 当您有多个项目时,这个 +会特别有用。 一般来说,您可以 +为**脚本**、**数据**和**文档**创建目录(文件夹)。 + +- **`data/`** 使用此文件夹存储您可能为特定分析的需要而创建的原始数据和中间 + 数据集。 为了 + 透明度和 + [来源](https://en.wikipedia.org/wiki/Provenance),您应该 + _始终_ 保留原始数据的副本,并尽可能多地以编程方式 (即使用 + 脚本,而不是手动) 完成 + 数据清理和预处理。 将原始数据 + 与处理后的数据分开也是一个好主意。 例如,你可以将 + 文件“data/raw/tree_survey.plot1.txt”和“...plot2.txt”与 + 由 + “scripts/01.preprocess.tree_survey.R”脚本生成的“data/processed/tree.survey.csv”文件分开保存。 +- **`documents/`** 这里用来保存大纲、草稿、 + 和其他文本。 +- **`scripts/`**(或`src`)这将是保存用于不同分析或绘图的 R + 脚本的位置,并且可能为您的函数保存一个 + 单独的文件夹(稍后会详细介绍)。 + +根据 +项目需求,您可能需要额外的目录或子目录,但这些应该构成您工作 +目录的骨干。 + +```{r, results="markup", fig.cap="Example of a working directory structure.", echo=FALSE, purl=FALSE, out.width="100%", fig.align="center"} +knitr::include_graphics("fig/working-directory-structure.png") +``` + +对于本课程,我们将需要一个 `data/` 文件夹来存储我们的原始数据 +并且当我们学习如何将数据导出为 +CSV 文件时,我们将使用 `data_output/`,以及 `fig_output/` 文件夹来存储我们将保存的图形。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战:创建项目目录结构 + +在屏幕右侧的“文件”选项卡下,单击“新建文件夹”并 +在新创建的工作目录 +内创建一个名为“data”的文件夹(例如,“~/bioc-intro/data”)。 (或者,在 R 控制台的 +处输入 `dir.create("data")`。) 重复这些操作来创建“data_output/”和 +“fig_output”文件夹。 + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +我们将把脚本保存在工作目录 +的根目录中,因为我们只使用一个文件,这将使事情 +更容易。 + +您的工作目录现在应如下所示: + +```{r, results="markup", fig.cap="How it should look like at the beginning of this lesson", echo=FALSE, purl=FALSE, out.width="100%", fig.align="center"} +knitr::include_graphics("fig/r-starting-how-it-should-look-like.png") +``` + +**项目管理**也适用于生物信息学项目, +当然[^bioindatascience]。 William Noble (@Noble:2009) 建议 +以下目录结构: + +[^bioindatascience]: 在本课程中,我们将生物信息学视为应用于生物或生物医学数据的 + 数据科学。 + +> 目录名称采用大字体,文件名采用较小的 +> 字体。 此处仅显示一部分文件。 Note that the +> dates are formatted `--` so that they can be +> sorted in chronological order. 源代码“src/ms-analysis.c” +> 被编译以创建“bin/ms-analysis”并记录在 +> “doc/ms-analysis.html”中。 数据目录 +> 中的 `README` 文件指定了谁在哪个 +> 日期从哪个 URL 下载了数据文件。 驱动脚本“results/2009-01-15/runall”自动 +> 生成三个子目录split1、split2 和 split3、 +> 对应三个交叉验证分割。 +> `bin/parse-sqt.py` 脚本被两个 `runall` 驱动程序 +> 脚本调用。 + +```{r bioinfoproj, fig.cap="Directory structure for a sample bioinformatics project.", out.width="100%", echo=FALSE} +knitr::include_graphics("fig/noble-bioinfo-project.png") +``` + +定义明确、记录良好的 +项目目录最重要的方面是,让不熟悉 +项目[^futureself] 的人能够 + +1. understand what the project is about, what data are available, what + analyses were run, and what results were produced and, most + importantly to + +2. 再次重复分析 - 使用新数据,或更改一些 + 分析参数。 + +[^futureself]: That someone could be, and very likely will be your + future self, a couple of months or years after the analyses were + run. + +### 工作目录 + +工作目录是一个需要理解的重要概念。 它是 R 查找和保存文件的 +位置。 当你 +为你的项目编写代码时,它应该引用与 +你的工作目录的根目录相关的文件,并且只需要这个 +结构内的文件。 + +使用 RStudio 项目可以轻松实现此目的并确保您的工作 +目录设置正确。 如果您需要检查它,您可以使用 +`getwd()`。 如果由于某种原因您的工作目录不是它 +应该的样子,您可以在 RStudio 界面中更改它,方法是在 +文件浏览器中导航到您的工作目录应该所在的位置,然后单击 +蓝色齿轮图标“更多”,然后选择“设置为工作目录”。 +或者,您可以使用 `setwd("/path/to/working/directory")` 来 +重置您的工作目录。 但是,您的脚本不应该包含 +这一行,因为它会在别人的计算机上失败。 + +**例子** + +下面的模式表示工作目录“bioc-intro”,其中包含 +“data”和“fig_output”子目录,以及后者中的 2 个文件: + +``` +bioc-intro/data/ + /fig_output/fig1.pdf + /fig_output/fig2.png +``` + +如果我们在工作目录中,我们可以使用相对路径“bioc-intro/fig_output/fig1.pdf”或 +绝对路径“/home/user/bioc-intro/fig_output/fig1.pdf”引用“fig1.pdf” +文件。 + +如果我们在“数据”目录中,我们将使用相对路径 +“../fig_output/fig1.pdf”或相同的绝对路径 +“/home/user/bioc-intro/fig_output/fig1.pdf”。 + +## 与 R 交互 + +编程的基础是我们写下 +计算机要遵循的指令,然后我们告诉计算机遵循那些 +指令。 我们用 R 编写或_编码_指令,因为它是一种 +通用语言,计算机和我们都能理解。 我们将 +指令称为 _命令_,并告诉计算机通过 _执行_(也称为 _运行_)这些命令来遵循 +指令。 + +与 R 交互的主要方式有两种:使用 +**控制台** 或使用 **脚本**(包含 +代码的纯文本文件)。 控制台窗格(在 RStudio 中,左下方面板)是 +用 R 语言编写的命令可以被计算机输入并 +立即执行的地方。 它还将显示已执行命令的结果 +。 您可以直接在控制台中输入 +命令,然后按 `Enter` 来执行那些 +命令,但是当您关闭会话时它们会被遗忘。 + +因为我们希望我们的代码和工作流程具有可重现性,所以最好 +在脚本编辑器中输入我们想要的命令,然后保存 +脚本。 这样,我们所做的事情就有了完整的记录,而且 +任何人(包括我们未来的自己!) 可以轻松地在他们的计算机上复制 +的结果。 但是请注意,仅在脚本中输入命令 +并不能自动_运行_它们 - 它们仍然需要通过 +发送到控制台进行执行。 + +RStudio 允许您使用 `Ctrl` + `Enter` 快捷键直接从脚本编辑器 +执行命令(在 Mac 上,`Cmd` + `Return` 也可以 +起作用)。 当您按下 `Ctrl` + +`Enter` 时,脚本中当前行的命令(光标指示为 +)或当前选定的文本 +中的所有命令将被发送到控制台并执行。 您可以在此 RStudio +有关 RStudio +IDE 的备忘单 中找到其他键盘快捷键。 + +在分析的某个阶段,您可能想要检查 +变量的内容或对象的结构,而不一定在脚本中保留它的 +记录。 You can type these commands and execute +them directly in the console. RStudio 提供了 `Ctrl` + `1` 和 +`Ctrl` + `2` 快捷键,允许您在脚本和 +控制台窗格之间跳转。 + +如果 R 准备好接受命令,R 控制台将显示 `>` 提示。 如果 +收到一个命令(通过键入、复制粘贴或使用 `Ctrl` + `Enter` 从脚本 +编辑器发送),R 将尝试执行它,并且当 +准备就绪时,将显示结果并返回一个新的 `>` 提示符以 +等待新命令。 + +If R is still waiting for you to enter more data because it isn't +complete yet, the console will show a `+` prompt. 这意味着你 +还没有输入完整的命令。 This is because you have +not 'closed' a parenthesis or quotation, i.e. you don't have the same +number of left-parentheses as right-parentheses, or the same number of +opening and closing quotation marks. 当这种情况发生时,如果你 +认为你已经完成了命令输入,请单击控制台 +窗口内并按 `Esc`;这将取消不完整的命令并且 +返回到 `>` 提示符。 + +## 如何在课程中和课程结束后学习更多知识? + +我们在本课程中涵盖的材料将为您提供初步的 +体验如何使用 R 分析数据以进行您自己的 +研究。 但是,您需要学习更多知识才能执行高级 +操作,例如清理数据集、使用统计方法、 +或创建漂亮的图形[^inthiscoure]。 The best way to become +proficient and efficient at R, as with any other tool, is to use it to +address your actual research questions. 对于初学者来说,从头开始编写脚本可能会让人感到 +畏惧,而考虑到许多 +人将他们的代码发布到网上,修改现有代码以 +满足你的目的可能会让你更容易上手。 + +[^inthiscoure]: 我们将在这里介绍其中的大部分内容(统计数据除外) + ,但只能触及使用 R 可以实现的 + 的丰富内容的表面。 + +```{r kitten, results="markup", echo=FALSE, purl=FALSE, out.width="400px", fig.align="center"} +knitr::include_graphics("fig/kitten-try-things.jpg") +``` + +## 寻求帮助 + +### 使用内置的 RStudio 帮助界面搜索有关 R 函数的更多信息 + +```{r rstudiohelp, fig.cap="RStudio help interface.", results="markup", echo=FALSE, purl=FALSE, out.width="70%", fig.align="center"} +knitr::include_graphics("fig/rstudiohelp.png") +``` + +获得帮助的最快方法之一是使用 RStudio 帮助 +界面。 默认情况下,该面板位于 RStudio 右下角 +面板。 如屏幕截图所示,通过输入单词 +“Mean”,RStudio 还会尝试提供一些您 +可能感兴趣的建议。 然后描述就会显示在显示 +窗口中。 + +### 我知道我想使用的函数的名称,但我不知道如何使用它 + +如果您需要有关特定函数的帮助,比如说 `barplot()`,您 +可以输入: + +```{r, eval=FALSE, purl=TRUE} +?barplot +``` + +如果您只需要提醒自己参数的名称,您可以使用: + +```{r, eval=FALSE, purl=TRUE} +args(lm) +``` + +### 我想使用一个执行 X 的函数,一定有一个函数可以执行该操作,但我不知道是哪一个...... + +如果您正在寻找一个函数来执行特定任务,您可以使用 +`help.search()`函数,它由双问号`??`调用。 +However, this only looks through the installed packages for help pages with a +match to your search request + +```{r, eval=FALSE, purl=TRUE} +??kruskal +``` + +如果您找不到所需内容,您可以使用 +[rdocumentation.org](https://www.rdocumentation.org) 网站,该网站通过所有可用软件包中的帮助文件进行搜索 +。 + +Finally, a generic Google or internet search "R \" will often either send +you to the appropriate package documentation or a helpful forum where someone +else has already asked your question. + +### 我被困住了…… 我收到一条我无法理解的错误消息 + +首先通过谷歌搜索错误信息。 但是,这种方法并不总是能很好地发挥作用 +因为通常包开发人员依赖于 R 提供的错误捕获功能。您 +最终会得到一般错误消息,而这些消息可能对诊断 +问题(例如“下标越界”)没有多大帮助。 如果消息非常通用,您 +可能还会在 +查询中包含您正在使用的函数或包的名称。 + +但是,您应该检查一下 Stack Overflow。 使用 `[r]` 标签搜索。 大多数 +问题已经得到解答,但挑战在于在搜索中使用正确的 +词来找到 +答案: + +[http://stackoverflow.com/questions/tagged/r](https://stackoverflow.com/questions/tagged/r) + +[R 简介](https://cran.r-project.org/doc/manuals/R-intro.pdf) 对于编程经验较少的人来说可能 +比较难懂,但是它是 +了解 R 语言基础知识的好地方。 + +[R FAQ](https://cran.r-project.org/doc/FAQ/R-FAQ.html) 内容密集且技术性很强 +但其中包含大量有用信息。 + +### 寻求帮助 + +获得他人帮助的关键是让他们迅速掌握 +你的问题。 You should make it as easy as possible to pinpoint where +the issue might be. + +尝试使用正确的词语来描述你的问题。 例如, +包与库不同。 大多数人会 +理解你的意思,但其他人对含义的差异有很强烈的感受 +。 The key point is that it can make +things confusing for people trying to help you. 描述问题时请尽可能精确( +)。 + +如果可能的话,尝试将不起作用的部分简化为一个简单的_可重现的 +示例_。 如果您可以使用非常小的数据 +框架而不是 50000 行和 10000 列的框架重现该问题,请提供 +小框架并描述您的问题。 在适当的时候,尝试 +来概括你正在做的事情,这样即使不在你的 +领域的人也能理解这个问题。 例如,不要使用真实数据集的 +子集,而是创建一个小的(3 列,5 行) +通用数据集。 有关如何编写可重现的 +示例的更多信息,请参阅 Hadley +Wickham 的这篇文章。 + +要与他人共享一个对象,如果它相对较小,您 +可以使用函数“dput()”。 它将输出可用于 +重新创建与内存中完全相同的对象: + +```{r, results="show", purl=TRUE} +## iris is an example data frame that comes with R and head() is a +## function that returns the first part of the data frame +dput(head(iris)) +``` + +如果对象较大,请提供原始文件(即您的 CSV +文件)以及您的脚本直到出现错误的位置(并且在 +之后删除与您的 +问题无关的所有内容)。 Alternatively, in particular if your question is not related +to a data frame, you can save any R object to a file[^export]: + +```{r, eval=FALSE, purl=FALSE} +saveRDS(iris, file="/tmp/iris.rds") +``` + +但是,该文件的内容不是人类可读的,并且无法 +直接发布在 Stack Overflow 上。 相反,它可以通过电子邮件发送给某个人 +,该人可以使用 `readRDS()` 命令阅读它(这里 +假设下载的文件位于 +用户主目录中的 `Downloads` 文件夹中): + +```{r, eval=FALSE, purl=FALSE} +some_data <- readRDS(file="~/Downloads/iris.rds") +``` + +最后,但同样重要的一点是,**始终包含 `sessionInfo()`** +的输出,因为它提供了有关您的平台、R 版本和 +您正在使用的软件包的重要信息,以及其他对 +理解您的问题非常有帮助的信息。 + +```{r, results="show", purl=TRUE} +sessionInfo() +``` + +### 去哪里寻求帮助? + +- 课程期间坐在您旁边的人。 不要犹豫, + 在研讨会期间与你的邻居交谈,比较你的答案, + 并寻求帮助。 +- 友好的同事:如果您认识某个比您更有经验 + 的人,他们也许能够并且愿意帮助您。 +- [Stack Overflow](https://stackoverflow.com/questions/tagged/r): 如果 + 你的问题之前没有被回答过并且回答得很好,那么 + 你很有可能在 5 分钟内得到答案。 Remember to + follow their guidelines on how to ask a good + question. +- R-help 邮件 + 列表:有 + 很多人 (包括大多数 R 核心团队成员) 阅读它,也有 + 很多人向其发帖,但其语气可能相当枯燥,并且对新用户并不总是 + 欢迎。 If your question is valid, you are + likely to get an answer very fast but don't expect that it will come + with smiley faces. 此外,在这里比在其他地方更重要的是,一定要确保 + 使用正确的词汇(否则您可能会得到一个指向 + 用词不当的答案,而不是回答您的 + 问题)。 如果您的问题是关于 + 基本函数而不是特定的包,您也会获得更多的成功。 +- 如果您的问题是关于特定软件包的,请查看是否有该软件包的 + 邮件列表。 通常它包含在包的描述文件 + 中,可以使用 + `packageDescription("name-of-package")` 来访问。 您可能还想尝试 + 直接给软件包的作者发送电子邮件,或者在 + 代码存储库(例如 GitHub)上打开一个问题。 +- 还有一些特定主题的邮件列表(GIS、 + 系统发育学等...),完整列表在 + [这里](https://www.r-project.org/mail.html)。 + +### 更多资源 + +- R 邮件列表的 [发帖指南](https://www.r-project.org/posting-guide.html)。 + +- 如何寻求 R + 帮助 + 有用的指南。 + +- Jon + Skeet 的这篇博客文章 + 对如何提出编程问题提供了相当全面的建议。 + +- [reprex](https://cran.rstudio.com/web/packages/reprex/) 包 + 在寻求 + 帮助时对于创建可重现的示例非常有帮助。 rOpenSci 社区呼吁“如何提出问题以便得到 + 答案”(Github + 链接 和 视频 + 录音)包括对 + reprex 包及其理念的介绍。 + +## R 包 + +### 加载包 + +正如我们上面看到的,R 包在 R 中起着基础性的作用。 +利用包的功能,假设它已安装,我们 +首先需要加载它才能使用它。 这是通过 +`library()` 函数完成的。 下面,我们加载“ggplot2”。 + +```{r loadp, eval=FALSE, purl=TRUE} +library("ggplot2") +``` + +### 安装软件包 + +The default package repository is The _Comprehensive R Archive +Network_ (CRAN), and any package that is available on CRAN can be +installed with the `install.packages()` function. 下面,例如, +我们安装稍后将了解的 `dplyr` 包。 + +```{r craninstall, eval=FALSE, purl=TRUE} +install.packages("dplyr") +``` + +此命令将安装“dplyr”包及其所有 +依赖项,即它所依赖的所有包。 + +另一个主要的 R 包存储库由 Bioconductor 维护。 [Bioconductor 软件包](https://bioconductor.org/packages/release/BiocViews.html#___Software) 使用专用软件包 +即 `BiocManager` 进行管理和安装,可以使用以下命令从 CRAN 安装: + +```{r, eval=FALSE, purl=TRUE} +install.packages("BiocManager") +``` + +Individual packages such as `SummarizedExperiment` (we will use it +later), `DESeq2` (for RNA-Seq analysis), and any others from either Bioconductor or CRAN can then be +installed with `BiocManager::install`. + +```{r, eval=FALSE, purl=TRUE} +BiocManager::install("SummarizedExperiment") +BiocManager::install("DESeq2") +``` + +默认情况下,`BiocManager::install()` 还将检查所有已安装的软件包,查看是否有可用的新版本。 如果有,它会向您显示并询问您是否要“更新全部/部分/无?” [a/s/n]:\`然后等待您的答复。 虽然您应该努力获得最新的软件包版本,但实际上我们建议仅在加载任何包之前在新的 R 会话中更新包。 + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- 开始使用 R 和 RStudio + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/zh/episodes/23-starting-with-r.Rmd b/locale/zh/episodes/23-starting-with-r.Rmd new file mode 100644 index 000000000..33cdef738 --- /dev/null +++ b/locale/zh/episodes/23-starting-with-r.Rmd @@ -0,0 +1,925 @@ +--- +source: Rmd +title: R 简介 +teaching: 60 +exercises: 60 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- 定义与 R 相关的以下术语:对象、分配、调用、函数、参数、选项。 +- 为 R 中的对象分配值。 +- 学习如何命名物体 +- 使用注释来告知脚本。 +- 解决 R 中的简单算术运算。 +- 调用函数并使用参数来改变其默认选项。 +- 检查向量的内容并操作其内容。 +- 从向量中取子集并提取值。 +- 分析缺失数据的向量。 + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- R 中的第一个命令 + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +> 本集基于 Data Carpentries 的_面向生态学家的 R 语言数据分析和 +> 可视化_课程。 + +## 在 R 中创建对象 + +只需在控制台中输入数学即可获得 R 的输出: + +```{r, purl=TRUE} +3 + 5 +12 / 7 +``` + +然而,为了做一些有用和有趣的事情,我们需要为 +_对象_分配\*值。 要创建一个对象,我们需要给它一个名字,后跟 +赋值运算符`<-`,以及我们想要赋予它的值: + +```{r, purl=TRUE} +weight_kg <- 55 +``` + +`<-` 是赋值运算符。 它将右侧的值分配给左侧的 +对象。 因此,执行 `x <- 3` 后,`x` 的值为 +`3`。 箭头可以读作 3 **进入** `x`。 由于历史 +原因,您也可以使用 `=` 进行赋值,但并非在每个 +上下文中都是如此。 由于语法上存在 +[细微差别](https://blog.revolutionanalytics.com/2008/12/use-equals-or-arrow-for-assignment.html) +,因此在赋值时始终使用 `<-` 是一种很好的做法。 + +在 RStudio 中,输入 Alt + \- (同时按下 Alt +和 \- 键)将在 PC 上的单个 +按键中写入 `<-`,而输入 Option + \- (同时按下 Option\- 键)则不会在单个 +按键中写入 `<-`。 +在 Mac 上也一样。 + +### 命名变量 + +对象可以被赋予任何名称,例如“x”、“current_temperature”或 +“subject_id”。 You want your object names to be explicit and not too +long. 它们不能以数字开头(`2x` 无效,但 `x2` +有效)。 R 区分大小写(例如,`weight_kg` 与 +`Weight_kg` 不同)。 有些名称不能使用,因为它们 +是 R 中基本函数的名称(例如,`if`、`else`、 +`for`,请参阅 +[此处](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Reserved.html) +了解完整列表)。 In general, even if it's allowed, it's best to +not use other function names (e.g., `c`, `T`, `mean`, `data`, `df`, +`weights`). 如果有疑问,请检查帮助以查看该名称是否已被 +使用。 最好避免在对象名称中使用点(“。”),如 +“my.dataset”。 由于历史原因,R 中有许多函数名称中带有点 +,但由于点在 R +(用于方法)和其他编程语言中具有特殊含义,因此最好避免使用 +它们。 还建议使用名词作为对象名称,使用动词 +作为函数名称。 保持代码 +样式的一致性(空格的位置、对象命名方式等)非常重要。 使用 +一致的编码风格可以让您的代码更清晰地供您 +未来的自己和您的合作者阅读。 在 R 中,一些流行的风格指南 +是 [Google 的](https://google.github.io/styleguide/Rguide.xml)、 +[tidyverse 的](https://style.tidyverse.org/) 风格和 Bioconductor +风格 +指南。 The +tidyverse's is very comprehensive and may seem overwhelming at +first. 您可以安装 +[**`lintr`**](https://github.com/jimhester/lintr) 包来 +自动检查代码样式中的问题。 + +> **Objects vs. variables**: What are known as `objects` in `R` are +> known as `variables` in many other programming languages. Depending +> on the context, `object` and `variable` can have drastically +> different meanings. However, in this lesson, the two words are used +> synonymously. 有关更多信息 +> [请参阅此处](https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Objects) + +当为一个对象分配值时,R 不会打印任何内容。 您 +可以使用括号或键入 +对象名称来强制 R 打印该值: + +```{r, purl=TRUE} +weight_kg <- 55 # doesn't print anything +(weight_kg <- 55) # but putting parenthesis around the call prints the value of `weight_kg` +weight_kg # and so does typing the name of the object +``` + +现在 R 内存中有了“weight_kg”,我们可以用它进行算术运算。 例如,对于 +来说,我们可能希望将这个重量转换为磅(磅重量是公斤重量的 2.2 倍): + +```{r, purl=TRUE} +2.2 * weight_kg +``` + +我们还可以通过分配新值来更改对象的值: + +```{r, purl=TRUE} +weight_kg <- 57.5 +2.2 * weight_kg +``` + +这意味着为一个对象分配一个值不会改变 +其他对象的值例如,让我们将动物的体重(磅)存储在一个新的 +对象`weight_lb`中: + +```{r, purl=TRUE} +weight_lb <- 2.2 * weight_kg +``` + +然后将“weight_kg”改为100。 + +```{r} +weight_kg <- 100 +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +您认为对象“weight_lb”的当前内容是什么? +126\.5 还是 220? + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## 评论 + +R 中的注释字符是 `#`, +脚本中 `#` 右边的任何内容都将被 R 忽略。在脚本中留下注释和 +解释很有用。 + +RStudio 可以轻松注释或取消注释一个段落:在 +选择要注释的行后,同时按下键盘上 +上的 Ctrl + Shift + C。 如果 +你只想注释掉一行,你可以将光标放在该行的任意 +位置(即不需要选择整行),然后 +按 Ctrl + Shift + C。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战 + +以下每个语句后面的值是什么? + +```{r, purl=TRUE} +mass <- 47.5 # mass? +age <- 122 # age? +mass <- mass * 2.0 # mass? +age <- age - 20 # age? +mass_index <- mass/age # mass_index? +``` + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## 函数及其参数 + +函数是“固定脚本”,可以自动执行更复杂的命令集 +,包括操作分配等。 Many functions are predefined, or can be +made available by importing R _packages_ (more on that later). 函数 +通常会获得一个或多个称为 _参数_ 的输入。 函数通常(但并非总是 +)返回一个 _值_。 一个典型的例子是函数“sqrt()”。 +输入(参数)必须是一个数字,返回值(实际上是 +输出)是该数字的平方根。 执行一个函数(“运行它”) +被称为_调用_该函数。 函数调用的一个示例是: + +```{r, eval=FALSE, purl=FALSE} +b <- sqrt(a) +``` + +这里,将 `a` 的值传递给 `sqrt()` 函数,`sqrt()` 函数 +计算平方根,并返回该值,然后将该值赋值给 +对象 `b`。 这个函数非常简单,因为它只接受一个参数。 + +函数的返回“值”不必是数字(如 `sqrt()` 的值), +并且它也不必是单个项:它可以是一组事物,或者 +甚至是一个数据集。 当我们将数据文件读入 R 时,我们就会看到这一点。 + +参数可以是任何东西,不仅是数字或文件名,还可以是其他 +对象。 每个参数的具体含义因函数而异,必须在文档中查找 +(见下文)。 一些函数接受的参数 +可以由用户指定,或者,如果省略,则采用_默认_值: +,这些被称为_选项_。 选项通常用于改变 +函数的运行方式,例如是否忽略“坏值”,或者 +在图中使用什么符号。 但是,如果您想要一些特定的东西,您可以指定一个您选择的值 +来代替默认值。 + +让我们尝试一个可以接受多个参数的函数:“round()”。 + +```{r, results="show", purl=TRUE} +round(3.14159) +``` + +在这里,我们仅用一个参数“3.14159”调用了“round()”,并且它 +返回了值“3”。 这是因为默认设置是四舍五入到最接近的 +整数。 如果我们想要更多的数字,我们可以通过获取有关“round”函数的 +信息来了解如何做到这一点。 我们可以使用“args(round)”或者使用“?round”查看此函数的 +帮助。 + +```{r, results="show", purl=TRUE} +args(round) +``` + +```{r, eval=FALSE, purl=TRUE} +?round +``` + +我们看到,如果我们想要不同数量的数字,我们可以 +输入“digits=2”或任意我们想要的数字。 + +```{r, results="show", purl=TRUE} +round(3.14159, digits = 2) +``` + +如果您按照定义参数的完全相同的顺序提供参数,则 +不必命名它们: + +```{r, results="show", purl=TRUE} +round(3.14159, 2) +``` + +如果你确实命名了参数,你可以切换它们的顺序: + +```{r, results="show", purl=TRUE} +round(digits = 2, x = 3.14159) +``` + +很好的做法是,在函数调用中将非可选参数(比如 +四舍五入的数字)放在第一位,并指定所有可选 +参数的名称。 如果你不这样做,阅读你代码的人可能必须查找具有不熟悉参数的函数的 +定义才能理解你在 +做什么。 通过指定参数的名称,您还可以保护 +免受函数接口将来可能发生的变化的影响,这些变化可能会 +在现有参数之间添加新参数。 + +## 向量和数据类型 + +向量是 R 中最常见、最基本的数据类型,基本上是 +R 的主力。向量由一系列值组成,例如 +数字或字符。 我们可以使用 +`c()` 函数为向量分配一系列值。 例如,我们可以创建一个动物体重向量,并将 +分配给一个新的对象“weight_g”: + +```{r, purl=TRUE} +weight_g <- c(50, 60, 65, 82) +weight_g +``` + +向量也可以包含字符: + +```{r, purl=TRUE} +molecules <- c("dna", "rna", "protein") +molecules +``` + +这里“dna”、“rna”等周围的引号至关重要。 如果没有 +引号,R 将假定存在名为 `dna`、`rna` 和 +`protein` 的对象。 由于这些对象在 R 的内存中不存在,因此会出现 +错误消息。 + +有许多函数可让您检查 +向量的内容。 `length()` 告诉你特定向量中有多少个元素: + +```{r, purl=TRUE} +length(weight_g) +length(molecules) +``` + +向量的一个重要特征是,所有元素都是 +相同类型的数据。 函数 `class()` 表示对象的类(元素的 +类型): + +```{r, purl=TRUE} +class(weight_g) +class(molecules) +``` + +函数“str()”概述了 +对象及其元素的结构。 在处理 +大型复杂对象时,它是一个很有用的函数: + +```{r, purl=TRUE} +str(weight_g) +str(molecules) +``` + +您可以使用 `c()` 函数将其他元素添加到向量中: + +```{r} +weight_g <- c(weight_g, 90) # 添加到向量末尾 +weight_g <- c(30, weight_g) # 添加到向量开头 +weight_g +``` + +在第一行中,我们取原始向量“weight_g”,将 +值“90”添加到其末尾,然后将结果保存回 +“weight_g”。 Then we add the value `30` to the beginning, again saving +the result back into `weight_g`. + +我们可以反复这样做来增加一个向量,或者组装一个 +数据集。 在我们编程时,这可能有助于添加我们正在 +收集或计算的结果。 + +**原子向量**是最简单的 R **数据类型**,是单一类型的线性 +向量。 上面,我们看到了 R 使用的 6 个主要**原子 +向量**类型中的 2 个:“字符”和“数字”(或 +“双精度”)。 这些是构建所有 R 对象 +的基本构建块。 其他 4 种 **原子向量** 类型是: + +- `“逻辑”` 表示 `TRUE` 和 `FALSE`(布尔数据类型) +- `“integer”` 表示整数(例如 `2L`,`L` 向 R + 表示它是一个整数) +- `“complex”` 表示具有实部和虚部 + 的复数(例如 `1 + 4i`),这就是我们要说的 +- “raw” 表示比特流,我们不会进一步讨论 + +您可以使用 `typeof()` 函数 +并输入您的向量作为参数来检查您的向量的类型。 + +向量是 R 使用的众多**数据结构**之一。 其他 +重要的是列表(`list`)、矩阵(`matrix`)、数据框 +(`data.frame`)、因子(`factor`)和数组(`array`)。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +我们已经看到,原子向量可以是字符类型、数字类型(或 +双精度型)、整数类型和逻辑类型。 但是如果我们尝试在一个向量中混合 +这些类型会发生什么? + +::::::::::::::: solution + +## 解决方案 + +R 隐式地将它们全部转换为同一类型 + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +每个例子中会发生什么? (提示:使用 `class()` 来 +检查对象的数据类型并输入其名称以查看会发生什么): + +```{r, eval=TRUE} +num_char <- c(1, 2, 3, "a") +num_logical <- c(1, 2, 3, TRUE, FALSE) +char_logical <- c("a", "b", "c", TRUE) +tricky <- c(1, 2, 3, "4") +``` + +::::::::::::::: solution + +## 解决方案 + +```{r, purl=TRUE} +class(num_char) +num_char +class(num_logical) +num_logical +class(char_logical) +char_logical +class(tricky) +tricky +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +您认为为什么会发生这种情况? + +::::::::::::::: solution + +## 解决方案 + +向量只能是一种数据类型。 R 尝试转换(强制) +该向量的内容以找到 +不会丢失任何信息的 _共同点_。 + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +以下示例中,`combined_logical` 中有多少个值为 `“TRUE”`(作为字符) +: + +```{r, eval=TRUE} +num_logical <- c(1, 2, 3, TRUE) +char_logical <- c("a", "b", "c", TRUE) +combined_logical <- c(num_logical, char_logical) +``` + +::::::::::::::: solution + +## 解决方案 + +只有一个。 没有过去数据类型的记忆,并且强制 +发生在第一次评估向量时。 因此,`num_logical` 中的 `TRUE` +在 `combined_logical` 中的 +转换为 `"1"` 之前,会先转换为 `1`。 + +```{r} +combined_logical +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +在 R 中,我们将对象从一个类转换为另一个类称为 +_强制_。 这些转换根据层次结构进行, +,某些类型优先被强制转换为其他类型。 Can +you draw a diagram that represents the hierarchy of how these data +types are coerced? + +::::::::::::::: solution + +## 解决方案 + +逻辑 → 数字 → 字符 ← 逻辑 + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +```{r, echo=FALSE, eval=FALSE, purl=TRUE} +## We've seen that atomic vectors can be of type character, numeric, integer, and +## logical. But what happens if we try to mix these types in a single +## vector? + +## What will happen in each of these examples? (hint: use `class()` to +## check the data type of your object) +num_char <- c(1, 2, 3, "a") + +num_logical <- c(1, 2, 3, TRUE) + +char_logical <- c("a", "b", "c", TRUE) + +tricky <- c(1, 2, 3, "4") + +## Why do you think it happens? + +## You've probably noticed that objects of different types get +## converted into a single, shared type within a vector. In R, we call +## converting objects from one class into another class +## _coercion_. These conversions happen according to a hierarchy, +## whereby some types get preferentially coerced into other types. Can +## you draw a diagram that represents the hierarchy of how these data +## types are coerced? +``` + +## 向量子集 + +如果我们想从一个向量中提取一个或多个值,我们必须 +在方括号中提供一个或多个索引。 例如: + +```{r, results="show", purl=TRUE} +molecules <- c("dna", "rna", "peptide", "protein") +molecules[2] +molecules[c(3, 2)] +``` + +我们还可以重复索引来创建一个比原始对象具有更多元素 +的对象: + +```{r, results="show", purl=TRUE} +more_molecules <- molecules[c(1, 2, 3, 2, 1, 4)] +more_molecules +``` + +R 索引从 1 开始。 Fortran、MATLAB、 +Julia 和 R 等编程语言从 1 开始计数,因为这是人类 +通常所做的。 C 系列语言(包括 C++、Java、Perl、 +和 Python)从 0 开始计数,因为这对于计算机来说更简单。 + +最后,还可以使用负索引获取向量 +的所有元素,除了一些指定元素: + +```{r} +molecules ## all molecules +molecules[-1] ## all but the first one +molecules[-c(1, 3)] ## all but 1st/3rd ones +molecules[c(-1, -3)] ## all but 1st/3rd ones +``` + +## 条件子集 + +另一种常见的子集方法是使用逻辑向量。 `TRUE` 将 +选择具有相同索引的元素,而 `FALSE` 则不会: + +```{r, purl=TRUE} +weight_g <- c(21, 34, 39, 54, 55) +weight_g[c(TRUE, FALSE, TRUE, TRUE, FALSE)] +``` + +通常,这些逻辑向量不是手工输入的,而是其他函数或逻辑测试的 +输出。 例如,如果您 +只想选择 50 以上的值: + +```{r, purl=TRUE} +## will return logicals with TRUE for the indices that meet +## the condition +weight_g > 50 +## so we can use this to select only the values above 50 +weight_g[weight_g > 50] +``` + +您可以使用 `&`(两个条件都为真, +AND)或 `|`(至少有一个条件为真,OR)组合多个测试: + +```{r, results="show", purl=TRUE} +weight_g[weight_g < 30 | weight_g > 50] +weight_g[weight_g >= 30 & weight_g == 21] +``` + +这里,`<` 代表“小于”,`>` 代表“大于”,`>=` 代表 +“大于或等于”,`==` 代表“等于”。 双等号 +符号 `==` 用于测试左右两边 +之间是否数值相等,不要与单个 `=` 符号混淆,后者 +执行变量赋值(类似于 `<-`)。 + +一个常见的任务是在向量中搜索某些字符串。 人们可以 +使用“或”运算符 `|` 来测试多个值是否相等,但是 +这很快就会变得乏味。 函数 `%in%` 允许您 +测试是否找到搜索向量的任何元素: + +```{r, purl=TRUE} +molecules <- c("dna", "rna", "protein", "peptide") +molecules[molecules == "rna" | molecules == "dna"] # returns both rna and dna +molecules %in% c("rna", "dna", "metabolite", "peptide", "glycerol") +molecules[molecules %in% c("rna", "dna", "metabolite", "peptide", "glycerol")] +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +你能弄清楚为什么 `"four" > "five"` 返回 `TRUE` 吗? + +::::::::::::::: solution + +## 解决方案 + +```{r} +"four" > "five" +``` + +在字符串上使用 `>` 或 `<` 时,R 会比较它们的字母顺序。 +这里的“four”位于“five”之后,因此大于 +它。 + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## 名字 + +可以命名向量的每个元素。 下面的代码块 +显示了没有任何名称的初始向量,如何设置名称,以及如何检索 +。 + +```{r} +x <- c(1, 5, 3, 5, 10) +names(x) ## no names +names(x) <- c("A", "B", "C", "D", "E") +names(x) ## now we have names +``` + +当向量具有名称时,除了索引之外,还可以通过其 +名称来访问元素。 + +```{r} +x[c(1, 3)] +x[c("A", "C")] +``` + +## 缺失数据 + +由于 R 旨在分析数据集,因此它包含 +缺失数据的概念(这在其他编程 +语言中并不常见)。 缺失数据在向量中表示为“NA”。 + +When doing operations on numbers, most functions will return `NA` if +the data you are working with include missing values. 此功能 +使您更难忽视处理 +缺失数据的情况。 您可以添加参数“na.rm = TRUE”来计算 +结果,同时忽略缺失值。 + +```{r} +heights <- c(2, 4, 4, NA, 6) +mean(heights) +max(heights) +mean(heights, na.rm = TRUE) +max(heights, na.rm = TRUE) +``` + +If your data include missing values, you may want to become familiar +with the functions `is.na()`, `na.omit()`, and `complete.cases()`. 请参阅下文 +中的示例。 + +```{r} +## 提取那些不是缺失值的元素。 +heights[!is.na(heights)] + +## 返回删除了不完整案例的对象。 +## 返回的对象是类型为 `"numeric"` 的原子向量 +## (或 `"double"`)。 +na.omit(heights) + +## 提取那些完整案例的元素。 +## 返回的对象是类型为 `"numeric"` 的原子向量 +## (或 `"double"`)。 +heights[complete.cases(heights)] +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +1. 使用这个以英寸为单位的高度向量,创建一个删除了 NA 的新向量。 + +```{r} +高度 <- c(63, 69, 60, 65, NA, 68, 61, 70, 61, 59, 64, 69, 63, 63, NA, 72, 65, 64, 70, 63, 65) +``` + +2. 使用函数“median()”计算“高度”向量的中值。 +3. 使用 R 找出集合中有多少人的身高超过 67 英寸。 + +::::::::::::::: solution + +## 解决方案 + +```{r, purl=TRUE} +heights_no_na <- heights[!is.na(heights)] +## 或 +heights_no_na <- na.omit(heights) +``` + +```{r, purl=TRUE} +median(heights, na.rm = TRUE) +``` + +```{r, purl=TRUE} +高度_高于_67 <- 高度_无_na[高度_无_na > 67] +长度(高度_高于_67) +``` + +::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## 生成向量 {#sec:genvec} + +```{r, echo=FALSE} +set.seed(1) +``` + +### 构造函数 + +存在一些函数来生成不同类型的向量。 要 +生成一个数字向量,可以使用 `numeric()` +构造函数,并将输出向量的长度作为 +参数。 这些值将被初始化为 0。 + +```{r, purl=TRUE} +numeric(3) +numeric(10) +``` + +请注意,如果我们要求长度为 0 的数字向量,我们将获得 +: + +```{r, purl=TRUE} +numeric(0) +``` + +字符和逻辑值有类似的构造函数,分别名为 +`character()` 和 `logical()`。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +字符和逻辑向量的默认值是什么? + +::::::::::::::: solution + +## 解决方案 + +```{r, purl=TRUE} +character(2) ## 空字符 +logical(2) ## FALSE +``` + +::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +### 复制元素 + +`rep` 函数允许将一个值重复一定次数 +次。 例如,如果我们想要用 +值 -1 来初始化一个长度为 5 的数字向量,我们可以执行以下操作: + +```{r, purl=TRUE} +rep(-1, 5) +``` + +类似地,要生成一个填充了缺失值的向量, +通常是一个很好的开始方式,而无需对要收集的数据 +设定假设: + +```{r, purl=TRUE} +rep(NA, 5) +``` + +`rep` 可以将任意长度的向量作为输入(上面,我们使用了长度为 1 的向量 +)和任何类型。 例如,如果我们想重复 +值 1、2 和 3 五次,我们可以执行以下操作: + +```{r, purl=TRUE} +rep(c(1, 2, 3), 5) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +如果我们想重复值 1、2 和 3 五次,但 +却按顺序获得五个 1、五个 2 和五个 3,该怎么办? 有两种 +可能性 - 请参阅 `?rep` 或 `?sort` 寻求帮助。 + +::::::::::::::: solution + +## 解决方案 + +```{r, purl=TRUE} +rep(c(1, 2, 3), each = 5) +sort(rep(c(1, 2, 3), 5)) +``` + +::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +### 序列生成 + +另一个非常有用的函数是“seq”,用于生成一个 +数字序列。 例如,为了以 2 为步长生成从 1 到 20 +的整数序列,可以使用: + +```{r, purl=TRUE} +seq(from = 1, to = 20, by = 2) +``` + +`by` 的默认值为 1,并且鉴于经常使用以 1 为步长生成一个值到另一个值的 +序列, +有一个快捷方式: + +```{r, purl=TRUE} +seq(1, 5, 1) +seq(1, 5) ## 默认为 +1:5 +``` + +要生成最终长度为 3, +的从 1 到 20 的数字序列,可以使用: + +```{r, purl=TRUE} +seq(from = 1, to = 20, length.out = 3) +``` + +### 随机样本和排列 + +最后一组有用的函数是那些生成随机 +数据的函数。 第一个,“样本”,生成另一个向量的随机排列 +。 例如,为了对 10 名学生 +口语考试进行随机排序,我首先为每个学生分配一个从 1 到 10 的数字(例如 +根据他们姓名的字母顺序排列),然后: + +```{r, purl=TRUE} +sample(1:10) +``` + +如果没有进一步的参数,“sample”将返回向量中所有 +元素的排列。 如果我想要一个特定大小的随机样本,我 +会将该值设置为第二个参数。 下面,我从预定义的“字母”向量中的字母表中随机抽取 5 个 +个字母: + +```{r, purl=TRUE} +sample(letters, 5) +``` + +如果我想要一个大于输入向量的输出,或者能够 +多次绘制一些元素,我需要将`replace` +参数设置为`TRUE`: + +```{r, purl=TRUE} +sample(1:5, 10, replace = TRUE) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +当尝试上述函数时,您将意识到 +样本确实是随机的,并且不会两次得到相同的 +排列。 To be able to reproduce these random draws, one can +set the random number generation seed manually with `set.seed()` +before drawing the random sample. + +和你的邻居一起测试此功能。 首先独立绘制两个随机的 +排列 `1:10`,并观察是否得到了 +个不同的结果。 + +现在设置种子,例如`set.seed(123)`并重复 +随机抽取。 注意,您现在获得相同的随机抽取。 + +通过设置不同的种子来重复。 + +::::::::::::::: solution + +## 解决方案 + +不同的排列 + +```{r, purl=TRUE} +sample(1:10) +sample(1:10) +``` + +与种子 123 相同的排列 + +```{r, purl=TRUE} +set.seed(123) +sample(1:10) +set.seed(123) +sample(1:10) +``` + +不同的种子 + +```{r, purl=TRUE} +set.seed(1) +sample(1:10) +set.seed(1) +sample(1:10) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +### 从正态分布中抽取样本 + +我们将要看到的最后一个函数是`rnorm`,它从正态分布中抽取一个随机的 +样本。 下面显示了两个均值 0 +和 100、标准差 1 和 5 的正态分布,分别记为 _N(0, 1)_ 和 +_N(100, 5)_。 + +```{r, echo=FALSE, fig.width=12, fig.height=6, fig.cap="Two normal distributions: *N(0, 1)* on the left and *N(100, 5)* on the right."} +par(mfrow = c(1, 2)) +plot(density(rnorm(1000)), main = "", sub = "N(0, 1)") +plot(density(rnorm(1000, 100, 5)), main = "", sub = "N(100, 5)") +``` + +三个参数 `n`、`mean` 和 `sd` 定义了 +样本的大小,以及正态分布的参数,即平均值 +及其标准差。 后者的默认值为0和1。 + +```{r, purl=TRUE} +rnorm(5) +rnorm(5, 2, 2) +rnorm(5, 100, 5) +``` + +现在我们已经学习了如何编写脚本,以及 R 的 +数据结构的基础知识,我们已经准备好开始处理更大的数据,并且 +了解数据框。 + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- 如何与 R 交互 + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/zh/episodes/25-starting-with-data.Rmd b/locale/zh/episodes/25-starting-with-data.Rmd new file mode 100644 index 000000000..6045898ed --- /dev/null +++ b/locale/zh/episodes/25-starting-with-data.Rmd @@ -0,0 +1,784 @@ +--- +source: 放射科 +title: 从数据开始 +teaching: 三十 +exercises: 三十 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- 描述什么是“data.frame”。 +- 将 .csv 文件中的外部数据加载到数据框中。 +- 总结数据框的内容。 +- 描述什么是因素。 +- 在字符串和因子之间转换。 +- 重新排序并重命名因素。 +- 格式化日期。 +- 导出并保存数据。 + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- 使用 R 进行首次数据分析 + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +> 本集基于 Data Carpentries 的_面向生态学家的 R 语言数据分析和 +> 可视化_课程。 + +## 基因表达数据的呈现 + +我们将使用 Blackmore 发布的部份数据,\* +上呼吸道感染对 +中枢神经系统转录组变化的影响\*。 该研究的目的是确定 +上呼吸道感染对感染后小脑和脊髓中发生的 +RNA 转录变化的影响。 性别匹配的八只 +周龄 C57BL/6 小鼠通过 +鼻内途径接种盐水或甲型流感病毒,并在第 0 +(未感染)、第 4 和第 8 天通过 RNA-seq 评估小脑和 +脊髓组织中的转录组变化。 + +数据集存储为逗号分隔值(CSV)文件。 每一行 +包含单个 RNA 表达测量的信息,前十一列 +代表: + +| 柱子 | 描述 | +| -- | -------------------- | +| 基因 | 被测量的基因名称 | +| 样本 | 测量基因表达的样本名称 | +| 表达 | 基因表达的价值 | +| 生物 | 生物体/物种 - 此处所有数据均来自小鼠 | +| 年龄 | 小鼠的年龄(这里所有的小鼠都是8周龄) | +| 性别 | 老鼠的性别 | +| 感染 | 小鼠的感染状态,即感染甲型流感或未感染。 | +| 拉紧 | A 型流感病毒株。 | +| 时间 | 感染持续时间(以天为单位)。 | +| 组织 | 用于基因表达实验的组织,即小脑或脊髓。 | +| 老鼠 | 鼠标唯一标识符。 | + +我们将使用 R 函数 `download.file()` 下载包含基因表达数据的 +CSV 文件,并使用 +`read.csv()` 将 CSV 文件的内容作为 +类 `data.frame` 的对象加载到内存中。 在 `download.file` 命令中, +第一个条目是带有源 URL 的字符串。 此源 URL +从 GitHub 存储库下载 CSV 文件。 +逗号后面的文本(“data/rnaseq.csv”)是该文件在您 +本地机器上的目标位置。 您需要在您的机器上建立一个名为 +`“data”`的文件夹,您将在该文件夹中下载文件。 因此,此命令下载 +远程文件,将其命名为“rnaseq.csv”并将其添加到名为“data”的预先存在的 +文件夹中。 + +```{r, eval=TRUE} +download.file(url = "https://github.com/carpentries-incubator/bioc-intro/raw/main/episodes/data/rnaseq.csv", + destfile = "data/rnaseq.csv") +``` + +您现在可以加载数据了: + +```{r, eval=TRUE, purl=TRUE} +rna <- read.csv("data/rnaseq.csv") +``` + +此语句不会产生任何输出,因为您可能 +还记得,分配不会显示任何内容。 如果我们想检查 +我们的数据是否已加载,我们可以通过 +输入其名称来查看数据框的内容: + +```{r, eval=FALSE} +rna +``` + +哇... 那是大量的输出。 至少这意味着数据已正确加载 +。 让我们使用函数“head()”检查这个数据框 +的顶部(前 6 行): + +```{r, purl=TRUE} +head(rna) +## Try also +## View(rna) +``` + +**笔记** + +`read.csv()` 假定字段由逗号分隔,但是在 +几个国家/地区,逗号用作小数分隔符,而 +分号 (;) 用作字段分隔符。 如果您想在 R 中读取 +这种类型的文件,您可以使用 `read.csv2()` 函数。 它的 +行为与 `read.csv()` 完全相同,但对 +小数点和字段分隔符使用不同的参数。 如果您使用另一种 +格式,则用户可以同时指定它们。 通过输入 `?read.csv` 查看 +`read.csv()` 的帮助以了解更多信息。 还有 +`read.delim()` 函数用于读取制表符分隔的数据文件。 值得注意的是 +所有这些函数实际上都是 +主`read.table()`函数的包装函数,具有不同的参数。 因此, +上述数据也可以通过使用 `read.table()` +以分隔参数 `,` 来加载。 代码如下: + +```{r, eval=TRUE, purl=TRUE} +rna <- read.table(file = "data/rnaseq.csv", + sep = ",", + header = TRUE) +``` + +必须将 header 参数设置为 TRUE 才能读取 +标题,因为默认情况下 `read.table()` 将 header 参数设置为 +FALSE。 + +## 什么是数据框? + +数据框是大多数表格数据的_事实上的_数据结构, +以及我们用于统计和绘图的数据结构。 + +A data frame can be created by hand, but most commonly they are +generated by the functions `read.csv()` or `read.table()`; in other +words, when importing spreadsheets from your hard drive (or the web). + +数据框是以表格 +格式表示的数据,其中列是所有具有相同长度的向量。 因为 +列是向量,所以每一列必须包含单一类型的数据 +(例如,字符、整数、因子)。 例如,这里有一个图 +,描绘了一个包含数字、字符和 +逻辑向量的数据框。 + +![](./图/数据框.svg) + +当我们用函数 `str()` 检查数据框 +的 str结构时,我们可以看到这一点: + +```{r} +str(rna) +``` + +## 检查 `data.frame` 对象 + +我们已经看到了函数“head()”和“str()”如何有助于 +检查数据框的内容和结构。 这里有一个 +非详尽的函数列表,可以帮助您了解 +数据的内容/结构。 让我们尝试一下吧! + +**尺寸**: + +- `dim(rna)` - 返回一个向量,其行数作为第一个 + 元素,列数作为第二个元素(对象的 + **维度**)。 +- `nrow(rna)`——返回行数。 +- `ncol(rna)`——返回列数。 + +**内容**: + +- `head(rna)`-显示前 6 行。 +- `tail(rna)`-显示最后 6 行。 + +**姓名**: + +- `names(rna)` - 返回列名(对于 + `data.frame` 对象,`colnames()` 的同义词)。 +- `rownames(rna)` - 返回行名称。 + +**概括**: + +- `str(rna)`——对象的结构和有关 + 类、长度和每列内容的信息。 +- `summary(rna)`——每列的汇总统计数据。 + +注意:这些函数大部分都是“通用的”,除了“data.frame”之外,它们还可以用于其他类型的 +对象。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +根据 `str(rna)` 的输出,你能回答以下 +个问题吗? + +- 对象“rna”的类别是什么? +- 这个对象有多少行、多少列? + +::::::::::::::: solution + +## 解决方案 + +- 类别:数据框 +- 行数:66465,列数:11 + +::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## 索引和子集数据框 + +我们的 `rna` 数据框有行和列(它有 2 个维度);如果我们 +想从中提取一些特定数据,我们需要指定我们想要的 +“坐标”。 行号在前,然后是 +列号。 但是,请注意,指定这些 +坐标的不同方式会导致不同类别的结果。 + +```{r, eval=FALSE, purl=TRUE} +# first element in the first column of the data frame (as a vector) +rna[1, 1] +# first element in the 6th column (as a vector) +rna[1, 6] +# first column of the data frame (as a vector) +rna[, 1] +# first column of the data frame (as a data.frame) +rna[1] +# first three elements in the 7th column (as a vector) +rna[1:3, 7] +# the 3rd row of the data frame (as a data.frame) +rna[3, ] +# equivalent to head_rna <- head(rna) +head_rna <- rna[1:6, ] +head_rna +``` + +`:` 是一个特殊函数,它按 +的升序或降序创建整数数值向量,例如对 +实例测试 `1:10` 和 `10:1`。 有关详细信息,请参阅部分@ref(sec:genvec)。 + +您还可以使用“-”符号排除数据框的某些索引: + +```{r, eval=FALSE, purl=TRUE} +rna[, -1] ## The whole data frame, except the first column +rna[-c(7:66465), ] ## Equivalent to head(rna) +``` + +数据框可以通过调用索引(如前所示) +进行子集化,也可以通过直接调用其列名进行子集化: + +```{r, eval=FALSE, purl=TRUE} +rna["gene"] # Result is a data.frame +rna[, "gene"] # Result is a vector +rna[["gene"]] # Result is a vector +rna$gene # Result is a vector +``` + +In RStudio, you can use the autocompletion feature to get the full and +correct names of the columns. + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战 + +1. 创建一个 `data.frame` (`rna_200`),其中仅包含 `rna` 数据集中 + 行 200 中的数据。 + +2. 注意“nrow()”如何给出“data.frame”中的行数? + +- 使用该数字提取初始 + `rna` 数据框中的最后一行。 + +- 将其与您看到的最后一行进行比较,使用`tail()`到 + 确保它符合预期。 + +- 使用“nrow()”而不是行号来拉出最后一行。 + +- 从最后一行创建一个新的数据框(“rna_last”)。 + +3. 使用 `nrow()` 提取位于 + `rna` 数据框中间的行。 将此行的内容存储在名为“rna_middle”的对象 + 中。 + +4. 将 `nrow()` 与上面的 `-` 符号结合起来,重现 `head(rna)` 的 + 行为,仅保留 rna 数据集的第一到第六个 + 行。 + +::::::::::::::: solution + +## 解决方案 + +```{r, purl=TRUE} +## 1. +rna_200 <- rna[200, ] +## 2. +## Saving `n_rows` to improve readability and reduce duplication +n_rows <- nrow(rna) +rna_last <- rna[n_rows, ] +## 3. +rna_middle <- rna[n_rows / 2, ] +## 4. +rna_head <- rna[-(7:n_rows), ] +``` + +::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## 因素 + +因素代表**分类数据**。 它们存储为与标签相关的整数 +,并且可以有序或无序。 While +factors look (and often behave) like character vectors, they are +actually treated as integer vectors by R. So you need to be very +careful when treating them as strings. + +一旦创建,因素只能包含一组预定义的值, +称为_级别_。 默认情况下,R 总是按字母顺序 +对级别进行排序。 例如,如果你有一个具有 2 个级别的因子: + +```{r, purl=TRUE} +sex <- factor(c("male", "female", "female", "male", "female")) +``` + +R 将为级别“女性”分配“1”,为级别 +“男性”分配“2”(因为“f”位于“m”之前,即使此向量中的第一个元素 +是“男性”)。 您可以使用函数 +`levels()` 来看到这一点,并且可以使用 `nlevels()` 来找到级别的数量: + +```{r, purl=TRUE} +levels(sex) +nlevels(sex) +``` + +有时,因素的顺序并不重要,有时你 +可能想要指定顺序,因为它很有意义(例如,“低”, +,“中”,“高”),它可以改善你的可视化,或者它是特定类型的分析所必需的 +。 这里,重新排序“性别”向量中的级别 +的一种方法是: + +```{r, purl=TRUE} +sex ## current order +sex <- factor(sex, levels = c("male", "female")) +sex ## after re-ordering +``` + +在 R 的内存中,这些因素由整数 (1, 2, 3) 表示, +但比整数更具信息量,因为因素是自我 +描述的:“女性”、“男性”比 `1`、 +`2` 更具描述性。 哪一个是“男性”? 您无法仅从 +整数数据来判断。 另一方面,因素本身就包含这些信息。 +当存在多个级别时它特别有用(例如我们的示例数据集中的 +基因生物型)。 + +当您的数据被存储为一个因子时,您可以使用 `plot()` +函数快速浏览每个因子级别所代表的观测值 +的数量。 让我们看看数据中的男性 +和女性的数量。 + +```{r firstfactorplot, fig.cap="Bar plot of the number of females and males.", purl=TRUE} +plot(sex) +``` + +### 转换为字符 + +如果您需要将因子转换为字符向量,则可以使用 +`as.character(x)`。 + +```{r, purl=TRUE} +as.character(sex) +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +### 重命名因素 + +如果我们想重命名这些因素,只需改变其 +级别即可: + +```{r, purl=TRUE} +levels(sex) +levels(sex) <- c("M", "F") +sex +plot(sex) +``` + +:::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +- 将“F”和“M”分别重命名为“女性”和“男性”。 + +::::::::::::::: solution + +## 解决方案 + +```{r, eval=TRUE, purl=TRUE} +levels(sex) +levels(sex) <- c("Male", "Female") +``` + +::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +我们已经看到了使用“read.csv()”时如何创建数据框,但是 +也可以使用“data.frame()”函数手动创建它们。 +这个手工制作的“data.frame”中存在一些错误。 你能 +发现并修复它们吗? 不要犹豫去尝试吧! + +```{r, eval=FALSE} +animal_data <- data.frame( + animal = c(dog, cat, sea cucumber, sea urchin), + feel = c("furry", "squishy", "spiny"), + weight = c(45, 8 1.1, 0.8)) +``` + +::::::::::::::: solution + +## 解决方案 + +- 动物名称周围缺少引号 +- “感觉”栏中缺少一项(可能是针对其中一种毛茸茸的动物) +- 体重栏缺少一个逗号 + +::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +您能预测以下 +示例中每一列的类别吗? + +使用 `str(country_climate)` 检查你的猜测: + +- 它们符合你的预期吗? 为什么? 为什么不? + +- 在创建数据框时,通过在最后一个 + 变量后添加 `stringsAsFactors = TRUE` 再试一次。 现在发生了什么事? + 当使用“read.csv()”将基于文本的 + 电子表格读入 R 时,也可以设置“stringsAsFactors”。 + +```{r, eval=FALSE, purl=TRUE} +country_climate <- data.frame( + country = c("Canada", "Panama", "South Africa", "Australia"), + climate = c("cold", "hot", "temperate", "hot/temperate"), + temperature = c(10, 30, 18, "15"), + northern_hemisphere = c(TRUE, TRUE, FALSE, "FALSE"), + has_kangaroo = c(FALSE, FALSE, FALSE, 1) + ) +``` + +::::::::::::::: solution + +## 解决方案 + +```{r, eval=TRUE, purl=TRUE} +country_climate <- data.frame( + country = c("Canada", "Panama", "South Africa", "Australia"), + climate = c("cold", "hot", "temperate", "hot/temperate"), + temperature = c(10, 30, 18, "15"), + northern_hemisphere = c(TRUE, TRUE, FALSE, "FALSE"), + has_kangaroo = c(FALSE, FALSE, FALSE, 1) + ) +str(country_climate) +``` + +::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +The automatic conversion of data type is sometimes a blessing, sometimes an +annoyance. 请注意它的存在,学习规则,并仔细检查您在 R 中导入的数据 +在您的数据框内是否属于正确类型。 如果没有,请利用它 +来检测在数据 +输入期间可能引入的错误(例如,某一列中应该只包含数字的字母)。 + +欲了解更多信息,请参阅 RStudio +教程 + +## 矩阵 + +在继续之前,既然我们已经了解了数据框,让我们 +回顾一下包安装并了解一种新的数据类型,即 +“矩阵”。 与“数据框”类似,矩阵有两个维度:行和 +列。 但主要的区别在于“矩阵”中的所有单元格必须 +属于同一类型:“数字”、“字符”、“逻辑”…… 从 +方面来看,矩阵更接近于“向量”而不是“数据框”。 + +矩阵的默认构造函数是“矩阵”。 它采用 +值的向量来填充矩阵和行数和/或 +列数[^ncol]。 这些值按照列排序,如下图所示 +。 + +```{r mat1, purl=TRUE} +m <- matrix(1:9, ncol = 3, nrow = 3) +m +``` + +[^ncol]: 行数或列数就足够了,因为另一个可以从值的长度推断出来。 尝试一下如果值和行数/列数不相加会发生什么。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +使用函数“installed.packages()”,创建一个“字符”矩阵 +,其中包含有关当前安装在 +计算机上的所有包的信息。 探索它。 + +::::::::::::::: solution + +## 解决方案: + +```{r pkg_sln, eval=FALSE, purl=TRUE} +## create the matrix +ip <- installed.packages() +head(ip) +## try also View(ip) +## number of package +nrow(ip) +## names of all installed packages +rownames(ip) +## type of information we have about each package +colnames(ip) +``` + +::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +创建大型随机数据矩阵作为测试 +数据通常很有用。 下面的练习要求你创建这样一个矩阵,其中包含从均值为 0、标准差为 +1 的正态分布中抽取的随机 +数据,这可以使用 `rnorm()` 函数完成。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +构建一个维度为 1000、长度为 3 的正态分布数据矩阵 +(平均值为 0,标准差为 1) + +::::::::::::::: solution + +## 解决方案 + +```{r rnormmat_sln, purl=TRUE} +set.seed(123) +m <- matrix(rnorm(3000), ncol = 3) +dim(m) +head(m) +``` + +::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## 格式化日期 + +最常见的问题之一是新手(和经验丰富的人!) R 用户有 +将日期和时间信息转换为 +适当且可在分析期间使用的变量。 + +### 注意电子表格程序中的日期 + +电子表格中的日期通常存储在单个列中。 虽然 +这似乎是记录日期最自然的方式,但实际上它并不是 +最佳做法。 电子表格应用程序将以 +看似正确的方式(对于人类观察者而言)显示日期,但它实际 +处理和存储日期的方式可能会有问题。 It is often much +safer to store dates with YEAR, MONTH and DAY in separate columns or +as YEAR and DAY-OF-YEAR in separate columns. + +电子表格程序,例如 LibreOffice、Microsoft Excel、OpenOffice、 +Gnumeric、... 有不同的(并且通常不兼容的)方式来编码 +日期(即使对于同一程序,不同版本和操作系统也存在不同的 +)。 此外,Excel 可以 将非日期的内容转换为 +日期 +(@Zeeberg:2004),例如 MAR1、DEC1、 +OCT4 等名称或标识符。 因此,如果您总体上避免使用日期格式,则 +更容易识别这些问题。 + +数据木工课程的 日期为 +数据 +部分提供了有关电子表格中日期缺陷的额外见解 +。 + +我们将使用包 +**`lubridate`** 中的 `ymd()` 函数(属于 **`tidyverse`**;了解更多信息 +[这里](https://www.tidyverse.org/))。 。 **`lubridate`** 作为 **`tidyverse`** 安装的一部分进行安装 +。 当你加载 +**`tidyverse`** (`library(tidyverse)`) 时,核心包(大多数数据分析中使用的 +包)也会被加载。 然而,**`lubridate`** +不属于核心 tidyverse,因此您必须使用 `library(lubridate)` 明确加载它 +。 + +首先加载所需的包: + +```{r loadlibridate, message=FALSE, purl=TRUE} +library("lubridate") +``` + +`ymd()` 采用代表年、月、日的向量,并将 +转换为 `Date` 向量。 `日期` 是 R 识别的一类数据, +表示日期,并且可以这样进行操作。 +函数所需的参数很灵活,但最佳实践是将字符 +向量格式化为“YYYY-MM-DD”。 + +让我们创建一个日期对象并检查其结构: + +```{r, purl=TRUE} +my_date <- ymd("2015-01-01") +str(my_date) +``` + +现在让我们分别粘贴年份、月份和日期——我们得到相同的结果: + +```{r, purl=TRUE} +# sep indicates the character to use to separate each component +my_date <- ymd(paste("2015", "1", "1", sep = "-")) +str(my_date) +``` + +现在让我们熟悉典型的日期操作 +管道。 The small data below has stored dates in different `year`, +`month` and `day` columns. + +```{r, purl=TRUE} +x <- data.frame(year = c(1996, 1992, 1987, 1986, 2000, 1990, 2002, 1994, 1997, 1985), + month = c(2, 3, 3, 10, 1, 8, 3, 4, 5, 5), + day = c(24, 8, 1, 5, 8, 17, 13, 10, 11, 24), + value = c(4, 5, 1, 9, 3, 8, 10, 2, 6, 7)) +x +``` + +现在我们将此函数应用于“x”数据集。 我们首先使用 `paste()` 从 `x` +的 `year`、`month` 和 `day` 列创建一个 +字符向量: + +```{r, purl=TRUE} +paste(x$year, x$month, x$day, sep = "-") +``` + +该字符向量可用作 `ymd()` 的参数: + +```{r, purl=TRUE} +ymd(paste(x$year, x$month, x$day, sep = "-")) +``` + +生成的 `Date` 向量可以添加到 `x` 作为名为 `date` 的新列: + +```{r, purl=TRUE} +x$date <- ymd(paste(x$year, x$month, x$day, sep = "-")) +str(x) # notice the new column, with 'date' as the class +``` + +让我们确保一切正常。 检查 +新列的一种方法是使用 `summary()`: + +```{r, purl=TRUE} +summary(x$date) +``` + +请注意,`ymd()` 需要按 +的顺序显示年、月、日。 例如,如果您有日、月和年,您将需要 +`dmy()`。 + +```{r, purl=TRUE} +dmy(粘贴(x$day, x$month, x$year, sep = "-")) +``` + +`lubdridate` 有许多函数可以解决所有日期变化。 + +## R 对象摘要 + +到目前为止,我们已经看到了几种类型的 R 对象,它们的维数 +不同,并且它们可以存储单个或多个数据 +类型: + +- **`向量`**:一维(有长度),单一类型的数据。 +- **`矩阵`**:二维,单一类型的数据。 +- **`data.frame`**:两个维度,每列一种类型。 + +## 列表 + +我们还没有见过这种数据类型,但了解它很有用,并且根据我们刚刚看到的总结, +是列表: + +- **`列表`**:一维,每个项目可以是不同的数据 + 类型。 + +下面,让我们创建一个包含数字、字符、 +矩阵、数据框和另一个列表的向量列表: + +```{r list0, purl=TRUE} +l <- list(1:10, ## 数字 + 字母, ## 字符 + installed.packages(), ## 矩阵 + 汽车, ## 数据框 + list(1, 2, 3)) ## 列表 +长度(l) +str(l) +``` + +列表子集化是使用 `[]` 来子集化新的子列表或使用 `[[]]` +来提取该列表的单个元素(使用索引或名称,如果 +列表已命名)。 + +```{r, purl=TRUE} +l[[1]] ## 第一个元素 +l[1:2] ## 长度为 2 的列表 +l[1] ## 长度为 1 的列表 +``` + +## 导出和保存表格数据 {#sec:exportandsave} + +我们已经了解了如何使用 +`read.table` 系列函数将基于文本的电子表格读入 R。 要将 `data.frame` 导出到 +基于文本的电子表格,我们可以使用 `write.table` 函数集 +(`write.csv`、`write.delim`,...)。 它们都将要导出的变量 +和要导出到的文件。 例如,要将 +`rna` 数据导出到 `data_output` +目录中的 `my_rna.csv` 文件,我们可以执行: + +```{r, eval=FALSE, purl=TRUE} +写入.csv(rna,文件 = “data_output/my_rna.csv”) +``` + +This new csv file can now be shared with other collaborators who +aren't familiar with R. Note that even though there are commas in some of +the fields in the `data.frame` (see for example the "product" column), R will +by default surround each field with quotes, and thus we will be able to +read it back into R correctly, despite also using commas as column +separators. + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- R 中的表格数据 + +::::::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/zh/episodes/30-dplyr.Rmd b/locale/zh/episodes/30-dplyr.Rmd new file mode 100644 index 000000000..d42549b80 --- /dev/null +++ b/locale/zh/episodes/30-dplyr.Rmd @@ -0,0 +1,1047 @@ +--- +source: 放射科 +title: 使用 dplyr 处理和分析数据 +teaching: 75 +exercises: 75 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- 描述\*\*`dplyr`**和**`tidyr`\*\*包的用途。 +- 描述一些对于 + 操作数据极其有用的函数。 +- 描述宽表和长表格式的概念,并了解 + 如何将数据框从一种格式重塑为另一种格式。 +- 演示如何连接表格。 + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- 使用 tidyverse 元包在 R 中进行数据分析 + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +```{r loaddata_dplyr2, echo=FALSE, purl=FALSE, message=FALSE} +if (!file.exists("data/rnaseq.csv")) +download.file(url = "https://github.com/carpentries-incubator/bioc-intro/raw/main/episodes/data/rnaseq.csv", + destfile = "data/rnaseq.csv") +``` + +> 本集基于 Data Carpentries 的_面向生态学家的 R 语言数据分析和 +> 可视化_课程。 + +## 使用 **`dplyr`** 和 **`tidyr`** 进行数据操作 + +Bracket subsetting is handy, but it can be cumbersome and difficult to +read, especially for complicated operations. + +当我们处理数据时,一些包可以极大地方便我们的任务。 +R 中的包基本上是一组附加函数,可让您 +做更多的事情。 我们迄今为止使用的函数,如 `str()` 或 +`data.frame()`,都是 R 内置的;加载包可以让您访问其他 +特定函数。 第一次使用包之前,您需要在您的机器上安装 +它,然后您应该在需要它时在每个后续的 +R 会话中导入它。 + +- 包\*\*`dplyr`\*\*为数据操作任务提供了强大的工具。 + 它被构建为直接与数据框一起工作,并且许多操作任务 + 已经进行了优化。 + +- 正如我们稍后会看到的,有时我们希望重塑数据框以便能够 + 进行一些特定的分析或进行可视化。 包\*\*`tidyr`\*\*解决了 + 这个常见的数据重塑问题,并提供了以整洁的方式操作 + 数据的工具。 + +如果要在研讨会结束后了解有关 **`dplyr`** 和 **`tidyr`** 的更多信息, +您可能需要查看这个 使用 + +和这个 关于 +。 + +- **`tidyverse`** 包是一个“总括包”,它安装了 + 几个用于数据分析的有用包,它们可以很好地协同工作, + 例如 **`tidyr`**、**`dplyr`**、**`ggplot2`**、**`tibble`** 等。 + 这些包帮助我们处理数据并与之交互。 + 它们允许我们对您的数据做很多事情,例如子集化、转换、 + 可视化等。 + +如果您已完成设置,则应该已经安装了 tidyverse 包。 +尝试从库中加载以检查您是否拥有它: + +```{r, message=FALSE, purl=TRUE} +## load the tidyverse packages, incl. dplyr +library("tidyverse") +``` + +如果您收到错误消息“没有名为‘tidyverse’的包”,那么您尚未 +为此版本的 R 安装该包。要安装\*\*`tidyverse`\*\*包类型: + +```{r, eval=FALSE, purl=TRUE} +BiocManager::install(“tidyverse”) +``` + +如果您必须安装\*\*`tidyverse`\*\*包,请不要忘记使用上面的`library()`命令在此 R 会话中加载它! + +## 使用 tidyverse 加载数据 + +我们不使用 `read.csv()`,而是使用 `read_csv()` +函数(注意用 `_` 而不是 `.`)读取数据,该函数来自 tidyverse 包 +**`readr`**。 + +```{r, message=FALSE, purl=TRUE} +rna <- read_csv("data/rnaseq.csv") + +## view the data +rna +``` + +请注意,数据类别现在被称为“tibble”。 + +Tibbles 调整了我们之前在 +中介绍的数据框对象的一些行为。 该数据结构与数据框非常相似。 对于我们的目的 +来说,唯一的区别是: + +1. 它在名称下显示每列的数据类型。 + 请注意,\<`dbl`\> 是一种数据类型,定义为保存带有 + 小数点的数值。 + +2. 它仅打印前几行数据,并且仅打印适合 + 一个屏幕的列数。 + +我们现在要学习一些最常见的 **`dplyr`** 函数: + +- `select()`:子集列 +- `filter()`:根据条件将行设为子集 +- `mutate()`:使用其他列的信息创建新列 +- `group_by()` 和 `summarise()`:对分组数据创建汇总统计数据 +- `arrange()`:对结果进行排序 +- `count()`:计数离散值 + +## 选择列和过滤行 + +要选择数据框的列,请使用“select()”。 该函数的第一个参数 +是数据框(`rna`),后续的 +参数是需要保留的列。 + +```{r, purl=TRUE} +select(rna, gene, sample, tissue, expression) +``` + +要选择除某些列之外的所有列,请在变量 +前面放置“-”以将其排除。 + +```{r, purl=TRUE} +select(rna, -tissue, -organism) +``` + +这将选择“rna”中除“tissue” +和“organism”之外的所有变量。 + +要根据特定标准选择行,请使用“filter()”: + +```{r, purl=TRUE} +filter(rna, sex == "Male") +filter(rna, sex == "Male" & infection == "NonInfected") +``` + +现在让我们假设我们对该数据集中分析的小鼠 +基因的人类同源物感兴趣。 该信息可以在 `rna` tibble 的 +最后一列中找到,名为 +`hsapiens_homolog_associated_gene_name`。 为了轻松地将其形象化,我们 +将创建一个新表,仅包含 2 列“基因”和 +“hsapiens_homolog_associated_gene_name”。 + +```{r} +genes <- select(rna, gene, hsapiens_homolog_associated_gene_name) +genes +``` + +一些小鼠基因没有人类同源物。 可以使用 +`filter()` 和 `is.na()` 函数检索这些,确定 +某物是否为 `NA`。 + +```{r, purl=TRUE} +filter(genes, is.na(hsapiens_homolog_associated_gene_name)) +``` + +如果我们只想保留具有人类同源物的小鼠基因,我们可以在 +中插入一个“!”符号来否定结果,因此我们要求在 hsapiens\_homolog\_associated\_gene\_name _不是_ +`NA` 的每一行中都为 +。 + +```{r, purl=TRUE} +filter(genes, !is.na(hsapiens_homolog_associated_gene_name)) +``` + +## 管道 + +如果您想同时选择和过滤怎么办? 有三种 +方法可以做到这一点:使用中间步骤、嵌套函数或管道。 + +通过中间步骤,您可以创建一个临时数据框并使用 +作为下一个函数的输入,如下所示: + +```{r, purl=TRUE} +rna2 <- filter(rna, sex == "Male") +rna3 <- select(rna2, gene, sample, tissue, expression) +rna3 +``` + +这是可读的,但会使您的工作区变得混乱,因为有大量的 +中间对象需要您单独命名。 由于有多个 +步骤,因此很难跟踪。 + +您还可以嵌套函数(即一个函数位于另一个函数内), +如下所示: + +```{r, purl=TRUE} +rna3 <- select(filter(rna, sex == "Male"), 基因, 样本, 组织, 表达) +rna3 +``` + +这很方便,但如果嵌套的函数太多,可能会难以阅读,因为 +R 从内到外评估表达式(在本例中,先过滤,然后选择)。 + +最后一个选项 _管道_ 是最近添加到 R 中的。管道让您可以将 +一个函数的输出直接发送到下一个函数,当您需要对同一个数据集执行许多操作时,这很有用 +。 + +R 中的管道看起来像 `%>%`(通过\*\*`magrittr`\*\* +包提供)或 `|>`(通过基础 R)。 如果您使用 RStudio,则可以在管道中输入 +和 Ctrl + Shift + M (如果您 +有 PC)或 Cmd + Shift + M (如果您 +有 Mac)。 + +在上面的代码中,我们使用管道首先将 `rna` 数据集 +通过 `filter()` 发送以保留 `sex` 为男性的行,然后通过 +`select()` 仅保留 `gene`、`sample`、`tissue` 和 +`expression` 列。 + +管道 `%>%` 将其左侧的对象直接作为 +传递给其右侧的函数的第一个参数,我们不再需要 +明确将数据框作为 `filter()` 和 +`select()` 函数的参数。 + +```{r, purl=TRUE} +rna %>% + filter(sex == "Male") %>% + select(gene, sample, tissue, expression) +``` + +有些人可能会发现将管道读成“then”这个词很有帮助。 例如,在上面的例子中, +我们取数据框 `rna`,_然后_我们 `过滤` +中含有 `sex == "Male"` 的行,_然后_我们 `选择` 列 `gene`、`sample`、 +`tissue` 和 `expression`。 + +**`dplyr`** 函数本身有些简单,但通过 +将它们与管道组合成线性工作流,我们可以完成 +更复杂的数据框操作。 + +如果我们想用这个较小版本的数据创建一个新对象,我们 +可以给它分配一个新名称: + +```{r, purl=TRUE} +rna3 <- rna %>% + filter(sex == "Male") %>% + select(gene, sample, organization, expression) + +rna3 +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +使用管道,对 `rna` 数据进行子集化,以保留时间 0 时雌性小鼠的观察结果, +其中基因表达高于 50000,并且仅保留列 +`基因`、`样本`、`时间`、`表达` 和 `年龄`。 + +::::::::::::::: solution + +## 解决方案 + +```{r} +rna %>% + filter(expression > 50000, + sex == "Female", + time == 0 ) %>% + select(gene, sample, time, expression, age) +``` + +::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## 合变 + +您经常需要根据现有 +列的值创建新列,例如进行单位转换,或者查找两个 +列中的值之比。 为此,我们将使用“mutate()”。 + +要创建以小时为单位的新时间列: + +```{r, purl=TRUE} +rna %>% + mutate(time_hours = time * 24) %>% + select(time, time_hours) +``` + +您还可以在同一个 `mutate()` 调用中根据第一个新列创建第二个新列: + +```{r, purl=TRUE} +rna %>% + mutate(time_hours = time * 24, + time_mn = time_hours * 60) %>% + select(time, time_hours, time_mn) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战 + +从满足以下 +条件的`rna`数据中创建一个新的数据框:仅包含`gene`、`chromosome_name`、 +`phenotype_description`、`sample`和`expression`列。 表达式 +值应该进行对数变换。 该数据框必须 +仅包含位于性染色体上、与 +表型描述相关且对数表达高于 5 的基因。 + +**提示**:思考一下应该如何排列命令来生成 +这个数据框! + +::::::::::::::: solution + +## 解决方案 + +```{r, eval=TRUE, purl=TRUE} +rna %>% + mutate(expression = log(expression)) %>% + select(gene, chromosome_name, phenotype_description, sample, expression) %>% + filter(chromosome_name == "X" | chromosome_name == "Y") %>% + filter(!is.na(phenotype_description)) %>% + filter(expression > 5) +``` + +::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## 拆分-应用-合并数据分析 + +许多数据分析任务可以使用 +_split-apply-combine_ 范式来完成:将数据分成组,对每组应用一些 +分析,然后合并结果。 **`dplyr`** +通过使用 `group_by()` 函数使这变得非常容易。 + +```{r} +rna %>% + group_by(gene) +``` + +`group_by()` 函数不执行任何数据处理,它 +将数据分组为子集:在上面的例子中,我们最初的 +`tibble` 的 `r nrow(rna)` 观测值根据 `gene` 变量被分成 +`r length(unique(rna$gene))` 组。 + +我们可以类似地决定根据样本对 tibble 进行分组: + +```{r} +rna %>% + group_by(样本) +``` + +这里我们最初的 `r nrow(rna)` 观测值的 `tibble` 被基于 `sample` 变量分成 +`r length(unique(rna$sample))` 组。 + +Once the data has been grouped, subsequent operations will be +applied on each group independently. + +### `summarise()` 函数 + +`group_by()` is often used together with `summarise()`, which +collapses each group into a single-row summary of that group. + +`group_by()` 将包含要计算摘要 +**分类** 变量的列名作为参数 +统计数据。 因此要计算基因的平均“表达”: + +```{r} +rna %>% + group_by(gene) %>% + summarise(mean_expression = mean(expression)) +``` + +我们还可能想计算每个样本中所有基因的平均表达水平: + +```{r} +rna %>% + group_by(sample) %>% + 总结(mean_expression = mean(expression)) +``` + +但我们也可以按多列分组: + +```{r} +rna %>% + group_by(gene, infection, time) %>% + summarise(mean_expression = mean(expression)) +``` + +一旦数据被分组,您还可以在同一 +时间总结多个变量(不一定是同一个变量)。 例如,我们可以添加一个 +列,表示基因和条件的中位“表达”: + +```{r, purl=TRUE} +rna %>% + group_by(gene, infection, time) %>% + summarise(mean_expression = mean(expression), + median_expression = median(expression)) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战 + +按时间点计算基因“Dok3”的平均表达水平。 + +::::::::::::::: solution + +## 解决方案 + +```{r, purl=TRUE} +rna %>% + filter(gene == "Dok3") %>% + group_by(time) %>% + summarise(mean = mean(expression)) +``` + +::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +### 数数 + +处理数据时,我们常常想知道每个因素或因素组合的观测值数量 +。 对于这个任务,**`dplyr`** 提供了 +`count()`。 例如,如果我们想要计算每个感染和未感染样本的 +的数据行数,我们会这样做: + +```{r, purl=TRUE} +rna %>% + count(infection) +``` + +`count()` 函数是我们已经见过的功能的简写:按变量分组,并通过计算该组中的观察次数进行汇总。 换句话说,`rna %>% count(infection)` 等同于: + +```{r, purl=TRUE} +rna %>% + group_by(感染) %>% + 总结(n = n()) +``` + +前面的例子显示了使用 `count()` 来计算_一个_因素(即`感染`)的行数/观察数 +。 +如果我们想要计算_多种因素的组合_,例如`感染`和`时间`, +我们会将第一个和第二个因素指定为`count()`的参数: + +```{r, purl=TRUE} +rna %>% + count(infection, time) +``` + +这相当于: + +```{r, purl=TRUE} +rna %>% + group_by(infection, time) %>% + summarise(n = n()) +``` + +有时对结果进行排序以方便比较是很有用的。 +我们可以使用`arrange()`对表格进行排序。 +例如,我们可能想按时间排列上面的表格: + +```{r, purl=TRUE} +rna %>% + count(infection, time) %>% + arrange(time) +``` + +或按计数: + +```{r, purl=TRUE} +rna %>% + count(infection, time) %>% + arrange(n) +``` + +为了按降序排序,我们需要添加 `desc()` 函数: + +```{r, purl=TRUE} +rna %>% + count(infection, time) %>% + arrange(desc(n)) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战 + +1. 每个样本分析了多少个基因? +2. 使用 `group_by()` 和 `summarise()` 来评估每个样本中的测序深度(所有计数的总和)。 哪个样本的测序深度最高? +3. 选择一个样本并根据生物型评估基因的数量。 +4. 识别与“异常 DNA 甲基化”表型描述相关的基因,并计算它们在时间 0、时间 4 和时间 8 的平均表达(以对数表示)。 + +::::::::::::::: solution + +## 解决方案 + +```{r} +## 1. +rna %>% + count(sample) +## 2. +rna %>% + group_by(sample) %>% + summarise(seq_depth = sum(expression)) %>% + range(desc(seq_depth)) +## 3. +rna %>% + filter(sample == "GSM2545336") %>% + count(gene_biotype) %>% + range(desc(n)) +## 4. +rna %>% + filter(phenotype_description == "异常 DNA 甲基化") %>% + group_by(gene, time) %>% + summarise(mean_expression = mean(log(expression))) %>% + range() +``` + +::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## 重塑数据 + +在 `rna` tibble 中,行包含表达值(单位),这些值 +与其他两个变量的组合相关:`gene` 和 `sample`。 + +All the other columns correspond to variables describing either +the sample (organism, age, sex, ...) 或基因(gene_biotype、ENTREZ_ID、product、...)。 +不随基因或样本而改变的变量在所有行中具有相同的值。 + +```{r} +rna %>% + arrange(gene) +``` + +这种结构称为“长格式”,因为一列包含所有值, +,而其他列列出值的上下文。 + +在某些情况下,“长格式”并不是真正的“人类可读的”,而另一种格式, +“宽格式”是首选,因为它是一种更紧凑的数据表示方式。 +这通常是基因表达值的情况,科学家习惯将 +视为矩阵,其中行代表基因,列代表样本。 + +因此,在这种格式下,可以直接通过 +来探索样本内基因表达水平之间的关系,以及通过 +来探索样本间的关系。 + +```{r, echo=FALSE} +rna %>% + select(gene, sample, expression) %>% + pivot_wider(names_from = sample, + values_from = expression) +``` + +为了将基因表达值从“rna”转换为宽格式 +,我们需要创建一个新表,其中“sample”列的值将 +成为列变量的名称。 + +这里的关键点是,我们仍然遵循 +整洁的数据结构,但是我们已经根据 +感兴趣的观察结果**重塑**了数据:每个基因的表达水平,而不是 +每个基因和每个样本记录它们的表达水平。 + +相反的转换是将列名转换为新变量的 +值。 + +我们可以使用两个 `tidyr` 函数完成这两种转换, +`pivot_longer()` 和 `pivot_wider()`(有关 +详细信息,请参阅 +[此处](https://tidyr.tidyverse.org/dev/articles/pivot.html))。 + +### 将数据转换为更广泛的格式 + +让我们选择“rna”的前三列并使用“pivot_wider()” +将数据转换为宽格式。 + +```{r, purl=TRUE} +rna_exp <- rna %>% + select(gene, sample, expression) +rna_exp +``` + +`pivot_wider` 有三个主要参数: + +1. 要转换的数据; +2. `names_from` :其值将成为新列 + 名称的列; +3. `values_from`:其值将填充新的 + 列的列。 + +```{r, fig.cap="`rna` 数据的宽枢轴。", echo=FALSE, message=FALSE} +knitr::include_graphics("fig/pivot_wider.png") + +``` + +```{r, purl=TRUE} +rna_wide <- rna_exp %>% + pivot_wider(names_from = sample, + values_from = expression) +rna_wide +``` + +请注意,默认情况下,“pivot_wider()”函数将为缺失值添加“NA”。 + +让我们想象一下,由于某种原因,某些样本中的某些 +基因缺少一些表达值。 在以下虚构的例子中,基因 Cyp2d22 在 GSM2545338 样本中只有 +一个表达值。 + +```{r, purl=TRUE} +rna_with_missing_values <- rna %>% + select(gene, sample, expression) %>% + filter(gene %in% c("Asl", "Apod", "Cyp2d22")) %>% + filter(sample %in% c("GSM2545336", "GSM2545337", "GSM2545338")) %>% + arrange(sample) %>% + filter(!(gene == "Cyp2d22" & sample != "GSM2545338")) +rna_with_missing_values +``` + +默认情况下,`pivot_wider()` 函数将为缺失的 +值添加 `NA`。 这可以通过 +`pivot_wider()` 函数的 `values_fill` 参数进行参数化。 + +```{r, purl=TRUE} +rna_with_missing_values %>% + pivot_wider(names_from = 样本, + values_from = 表达式) + +rna_with_missing_values %>% + pivot_wider(names_from = 样本, + values_from = 表达式, + values_fill = 0) +``` + +### 将数据转换为更长的格式 + +在相反的情况下,我们使用列名并将它们变成 +一对新变量。 一个变量将列名表示为 +值,另一个变量包含先前与列名相关联的 +值。 + +`pivot_longer()` 有四个主要参数: + +1. 要转换的数据; +2. `names_to`:我们希望创建的新列名,并用 + 当前列名填充; +3. `values_to`:我们希望创建的新列名,并用 + 当前值填充; +4. 用于填充“names_to”和 + “values_to”变量(或删除)的列的名称。 + +```{r, fig.cap="`rna` 数据的长枢轴。", echo=FALSE, message=FALSE} +knitr::include_graphics("fig/pivot_longer.png") + +``` + +要从 `rna_wide` 重新创建 `rna_long`,我们需要创建一个名为 `sample` 的键 +和一个名为 `expression` 的值,并使用除 `gene` 之外的所有列 +作为键变量。在这里,我们用减号删除 `gene` 列 +。 + +请注意这里如何引用新变量名称。 + +```{r} +rna_long <- rna_wide %>% + pivot_longer(names_to = "sample", + values_to = "expression", + -gene) +rna_long +``` + +我们还可以使用规范来指定 +包含哪些列。 如果您有大量可识别的 +列,这将非常有用,而且指定要收集的内容比指定要保留 +的内容更容易。 这里,`starts_with()` 函数可以帮助检索样本 +名称,而无需将它们全部列出! +另一种可能性是使用 `:` 运算符! + +```{r} +rna_wide %>% + pivot_longer(names_to = "sample", + values_to = "expression", + cols = starts_with("GSM")) +rna_wide %>% + pivot_longer(names_to = "sample", + values_to = "expression", + GSM2545336:GSM2545380) +``` + +请注意,如果我们在宽格式中缺少值,则`NA`将为 +,包含在新的长格式中。 + +记住我们之前包含缺失值的虚构 tibble: + +```{r} +rna_with_missing_values + +wide_with_NA <- rna_with_missing_values %>% + pivot_wider(names_from = sample, + values_from = expression) +wide_with_NA + +wide_with_NA %>% + pivot_longer(names_to = "sample", + values_to = "expression", + -gene) +``` + +转向更宽更长的格式可以成为平衡数据集 +的有效方法,这样每个重复都有相同的组成。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## 问题 + +从 rna 表开始,使用 `pivot_wider()` 函数创建 +一个宽格式表,给出每只小鼠的基因表达水平。 +然后使用`pivot_longer()`函数恢复长格式的表。 + +::::::::::::::: solution + +## 解决方案 + +```{r, answer=TRUE, purl=TRUE} +rna1 <- rna %>% +select(gene, mouse, expression) %>% +pivot_wider(names_from = mouse, values_from = expression) +rna1 + +rna1 %>% +pivot_longer(names_to = "mouse_id", values_to = "counts", -gene) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## 问题 + +从 `rna` 数据框中子集位于 X 和 Y 染色体上的基因,并以 +为列、以 `sex` 为列、以 `chromosome_name` 为 +为行、以位于每条染色体上的基因平均表达为值、以 +为值,将数据框扩展到以下表: + +```{r, echo=FALSE, message=FALSE} +knitr::include_graphics("fig/Exercise_pivot_W.png") +``` + +重塑之前需要先总结一下! + +::::::::::::::: solution + +## 解决方案 + +让我们首先从 +男性和女性样本中计算 X 和 Y 连锁基因的平均表达水平…… + +```{r} + rna %>% + filter(chromosome_name == "Y" | chromosome_name == "X") %>% + group_by(sex, chromosome_name) %>% + summarise(mean = mean(expression)) +``` + +并将表格旋转至宽格式 + +```{r, answer=TRUE, purl=TRUE} +rna_1 <- rna %>% + filter(chromosome_name == "Y" | chromosome_name == "X") %>% + group_by(sex, chromosome_name) %>% + summarise(mean = mean(expression)) %>% + pivot_wider(names_from = sex, + values_from = mean) + +rna_1 +``` + +现在获取该数据框并使用“pivot_longer()”对其进行转换,因此 +每行都是一个按“性别”组合唯一的“chromosome_name”。 + +```{r, answer=TRUE, purl=TRUE} +rna_1 %>% + pivot_longer(names_to = "gender", + values_to = "mean", + -chromosome_name) + +``` + +::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## 问题 + +使用 `rna` 数据集创建一个表达矩阵,其中每行 +代表基因的平均表达水平,每列代表 +不同的时间点。 + +::::::::::::::: solution + +## 解决方案 + +我们首先计算基因和时间的平均表达 + +```{r} +rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) +``` + +在使用pivot_wider()函数之前 + +```{r} +rna_time <- rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) +rna_time +``` + +请注意,这会生成一个 tibble,其中的一些列名以数字开头。 +如果我们想选择与时间点相对应的列, +我们不能直接使用列名…… 当我们选择第 4 列时会发生什么? + +```{r} +rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) %>% + select(gene, 4) +``` + +要选择时间点 4,我们必须用反引号“\\`”引用列名称 + +```{r} +rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) %>% + select(gene, `4`) +``` + +另一种可能性是重命名该列, +选择一个不以数字开头的名称: + +```{r} +rna %>% + group_by(gene, time) %>% + summarise(mean_exp = mean(expression)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) %>% + rename("time0" = `0`, "time4" = `4`, "time8" = `8`) %>% + select(gene, time4) +``` + +::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## 问题 + +使用包含每个时间点的平均表达水平的先前数据框并创建一个新列 +,其中包含时间点 8 和时间点 0 之间的倍数变化,以及时间点 8 和时间点 4 之间的倍数变化 +。 +将此表转换为长格式表,收集计算出的倍数变化。 + +::::::::::::::: solution + +## 解决方案 + +从 rna\_time tibble 开始: + +```{r} +rna_time +``` + +计算倍数变化: + +```{r} +rna_time %>% + mutate(time_8_vs_0 = `8` / `0`, time_8_vs_4 = `8` / `4`) +``` + +并使用pivot\_longer()函数: + +```{r} +rna_time %>% + mutate(time_8_vs_0 = `8` / `0`, time_8_vs_4 = `8` / `4`) %>% + pivot_longer(names_to = "comparisons", + values_to = "Fold_changes", + time_8_vs_0:time_8_vs_4) +``` + +::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## 连接表 + +在许多现实生活中,数据分布在多个表中。 +Usually this occurs because different types of information are +collected from different sources. + +对于某些分析来说,可能需要将两个或多个 +表中的数据基于所有表共有的 +列组合到单个数据框中。 + +`dplyr` 包提供了一组连接函数,用于根据指定列内的匹配组合两个 +数据框。 在这里,我们 +对连接进行简单介绍。 如需进一步阅读,请 +参阅有关 表 +连接 的章节。 +数据转换秘籍 +表 +还提供了关于表连接的简要概述。 + +我们将使用一个小表“rna_mini”来说明连接,我们将通过对原始“rna”表进行子集设置来创建它 +,只保留 3 +列和 10 行。 + +```{r} +rna_mini <- rna %>% + select(gene, sample, expression) %>% + head(10) +rna_mini +``` + +第二个表“annot1”包含2列,gene 和 +gene\_description。 您可以通过单击链接然后将其移动到“data/”文件夹来 +[下载 annot1.csv](https://carpentries-incubator.github.io/bioc-intro/data/annot1.csv) +,或者 +您可以使用下面的 R 代码将其直接下载到文件夹。 + +```{r, message=FALSE} +download.file(url = "https://carpentries-incubator.github.io/bioc-intro/data/annot1.csv", + destfile = "data/annot1.csv") +annot1 <- read_csv(file = "data/annot1.csv") +annot1 +``` + +我们现在要使用 `dplyr` 包中的 `full_join()` 函数将这两个表合并为一个包含所有 +变量的表。 +函数将自动找到与第一个和第二个表中的 +列匹配的公共变量。 在这种情况下,“基因”是常见的 +变量。 这样的变量被称为键。 键用于匹配不同表之间的 +观察结果。 + +```{r} +full_join(rna_mini, annot1) +``` + +在现实生活中,基因注释有时会被标记不同。 + +`annot2` 表与 `annot1` 完全相同,只是包含基因名称的 +变量的标签不同。 再次,要么 +自己 [下载 annot2.csv](https://carpentries-incubator.github.io/bioc-intro/data/annot2.csv) +并将其移动到 `data/`,要么使用下面的 R 代码。 + +```{r, message=FALSE} +download.file(url = "https://carpentries-incubator.github.io/bioc-intro/data/annot2.csv", + destfile = "data/annot2.csv") +annot2 <- read_csv(file = "data/annot2.csv") +annot2 +``` + +如果没有匹配的变量名,我们可以手动设置 +变量来用于匹配。 可以使用 +`by` 参数设置这些变量,如下面 `rna_mini` 和 `annot2` 表所示。 + +```{r} +full_join(rna_mini, annot2, by = c("gene" = "external_gene_name")) +``` + +从上可以看出,第一个表的变量名在连接后的表中保留为 +。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战: + +通过点击 +[此处](https://carpentries-incubator.github.io/bioc-intro/data/annot3.csv) +下载 `annot3` 表,并将该表放入您的数据/存储库中。 使用 `full_join()` +函数,连接表 `rna_mini` 和 `annot3`。 +基因 _Klk6_、_mt-Tf_、_mt-Rnr1_、_mt-Tv_、_mt-Rnr2_ 和 _mt-Tl1_ 发生了什么? + +::::::::::::::: solution + +## 解决方案 + +```{r, message=FALSE} +annot3 <- read_csv("data/annot3.csv") +full_join(rna_mini, annot3) +``` + +基因 _Klk6_ 仅存在于 `rna_mini` 中,而基因 _mt-Tf_、_mt-Rnr1_、_mt-Tv_、 +_mt-Rnr2_ 和 _mt-Tl1_ 仅存在于 `annot3` 表中。 表中 +变量的各自值已被编码为缺失。 + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## 导出数据 + +现在您已经了解了如何使用“dplyr”从 +中提取信息或总结原始数据,您可能希望导出这些新数据集以便与您的合作者共享 +或用于存档。 + +与用于将 CSV 文件读入 R 的 `read_csv()` 函数类似,有一个 +函数 `write_csv()`,可以从数据框生成 CSV 文件。 + +在使用“write_csv()”之前,我们将在工作目录中创建一个新文件夹“data_output”, +,用于存储生成的数据集。 我们不希望 +将生成的数据集写入与原始数据相同的目录中。 +将它们分开是一种很好的做法。 `data` 文件夹应该只包含 +原始、未改变的数据,并且应该保持不变以确保我们不会删除 +或修改它。 相反,我们的脚本将生成 `data_output` +目录的内容,因此即使它包含的文件被删除,我们也总是可以 +重新生成它们。 + +让我们使用`write_csv()`来保存我们之前创建的rna_wide表。 + +```{r, purl=TRUE, eval=FALSE} +write_csv(rna_wide,文件 = “data_output/rna_wide.csv”) +``` + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- 使用 tidyverse 元包在 R 中生成表格数据 + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/zh/episodes/40-visualization.Rmd b/locale/zh/episodes/40-visualization.Rmd new file mode 100644 index 000000000..5b31006f5 --- /dev/null +++ b/locale/zh/episodes/40-visualization.Rmd @@ -0,0 +1,1105 @@ +--- +source: 放射科 +title: 数据可视化 +teaching: 60 +exercises: 60 +--- + +```{r loaddata_vis, echo=FALSE, purl=FALSE, message=FALSE} +if (!file.exists("data/rnaseq.csv")) +download.file(url = "https://github.com/carpentries-incubator/bioc-intro/raw/main/episodes/data/rnaseq.csv", + destfile = "data/rnaseq.csv") +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- 使用 ggplot 生成散点图、箱线图、线图等。 +- 设置通用情节设置。 +- 描述什么是分面并在 ggplot 中应用分面。 +- 修改现有 ggplot 图的美观度(包括轴标签和颜色)。 +- 根据数据框中的数据构建复杂且定制的图表。 + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- R 中的可视化 + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +```{r vis_setup, echo=FALSE} +rna <- read.csv("data/rnaseq.csv") +``` + +> 本集基于 Data Carpentries 的_面向生态学家的 R 语言数据分析和 +> 可视化_课程。 + +## 数据可视化 + +我们首先加载所需的包。 **`ggplot2`** 包含在 +**`tidyverse`** 包中。 + +```{r load-package, message=FALSE, purl=TRUE} +library("tidyverse") +``` + +如果还不在工作区中,请加载我们在上一节 +课中保存的数据。 + +```{r load-data, eval=FALSE, purl=TRUE} +rna <- read.csv("data/rnaseq.csv") +``` + +数据可视化秘籍 +表 +将涵盖 `ggplot2` 的基础知识和更高级的功能,并且除了作为提醒之外,还将 +帮助您概览 +包中可用的许多数据表示。 以下由 Thomas Lin Pedersen +制作的视频 +教程 ([第 1 部分](https://www.youtube.com/watch?v=h29g21z0a68) 和 +[2](https://www.youtube.com/watch?v=0m4yywqNPVY)) 也非常具有启发性。 + +## 使用 `ggplot2` 绘图 + +`ggplot2` 是一个绘图包,可以很容易地从数据框中的数据创建复杂的 +图。 它提供了一个更具程序性的 +界面,用于指定要绘制的变量、如何显示它们、 +以及一般的视觉属性。 支持 +`ggplot2`的理论基础是_图形语法_(@Wilkinson:2005)。 使用这种 +方法,如果基础数据发生变化,我们只需要进行最少的更改;如果我们决定从条形图更改为散点图,则只需要进行 +更改。 这有助于 +以最少的调整 +和微调创建出版质量的图表。 + +有一本关于“ggplot2”(@ggplot2book)的书提供了很好的 +概述,但它已经过时了。 第三版正在准备中, +将[免费在线提供](https://ggplot2-book.org/)。 `ggplot2` +网页 ([https://ggplot2.tidyverse.org](https://ggplot2.tidyverse.org)) 提供了充足的文档。 + +`ggplot2` 的功能类似于“长”格式的数据,即每个维度为 +一列,每个观察值为一行。 结构良好的数据 +将在使用“ggplot2”制作图形时为您节省大量时间。 + +ggplot 图形是通过添加新元素一步步构建的。 以这种方式添加 +层可以实现广泛的灵活性和 +图的定制。 + +> 图形语法背后的想法是,你可以从相同的 3 个组件构建每个 +> 图形:(1) 数据集,(2) 坐标系, +> 和 (3) 几何对象 - 即表示数据点的视觉标记 \[^three\\_comp\\_ggplot2] + +[^three_comp_ggplot2]: 来源:[数据可视化备忘单](https://raw.githubusercontent.com/rstudio/cheatsheets/main/data-visualization.pdf)。 + +为了构建 ggplot,我们将使用以下基本模板,该模板可以 +用于不同类型的绘图: + +``` +ggplot(data = , mapping = aes()) + () +``` + +- 使用 `ggplot()` 函数并使用 `data` 参数将图绑定到特定的 **data + 框架** + +```{r, eval=FALSE} +ggplot(data = rna) +``` + +- 定义一个**映射**(使用美学(`aes`)函数),通过 + 选择要绘制的变量并指定如何在图形中呈现 + 它们,例如作为 x/y 位置或特征,如 + 大小、形状、颜色等。 + +```{r, eval=FALSE} +ggplot(data = rna, mapping = aes(x = expression)) +``` + +- 添加'**geoms**' - 几何图形,或图中 + 数据的图形表示(点、线、条)。 `ggplot2` 提供许多 + 不同的几何对象;今天我们将使用一些常见的,包括: + + ``` + * `geom_point()` 用于散点图、点图等。 + * `geom_histogram()` 用于直方图! + * `geom_boxplot()` 用于箱线图! + * `geom_line()` 用于趋势线、时间序列等。 + ``` + +要向图中添加几何图形,请使用“+”运算符。 让我们首先使用 +`geom_histogram()`: + +```{r first-ggplot, cache=FALSE, purl=TRUE} +ggplot(data = rna, mapping = aes(x = expression)) + + geom_histogram() +``` + +`ggplot2` 包中的 `+` 特别有用,因为它 +允许您修改现有的 `ggplot` 对象。 这意味着您可以 +轻松设置绘图模板并方便地探索不同类型的 +绘图,因此上述绘图也可以使用如下代码生成: + +```{r, eval=FALSE, purl=TRUE} +# Assign plot to a variable +rna_plot <- ggplot(data = rna, + mapping = aes(x = expression)) + +# Draw the plot +rna_plot + geom_histogram() +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战 + +您可能已经注意到,在 +绘制直方图时会出现一条自动消息: + +```{r, echo=FALSE, fig.show="hide"} +ggplot(rna, aes(x = expression)) + + geom_histogram() +``` + +将 `geom_histogram()` 的参数 `bins` 或 `binwidth` 更改为 +以更改箱的数量或宽度。 + +::::::::::::::: solution + +## 解决方案 + +```{r, purl=TRUE} +# change bins +ggplot(rna, aes(x = expression)) + + geom_histogram(bins = 15) + +# change binwidth +ggplot(rna, aes(x = expression)) + + geom_histogram(binwidth = 2000) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +我们可以在这里观察到数据向右倾斜。 我们可以应用 +log2 变换来获得更加对称的分布。 请注意,我们 +在这里添加一个小的常数值(`+1`)以避免当表达式值等于 0 时返回 `-Inf` 值 +。 + +```{r log-transfo, cache=FALSE, purl=TRUE} +rna <- rna %>% + mutate(expression_log = log2(expression + 1)) +``` + +如果我们现在绘制 log2 变换表达式的直方图, +分布确实更接近正态分布。 + +```{r second-ggplot, cache=FALSE, purl=TRUE} +ggplot(rna, aes(x = expression_log)) + geom_histogram() +``` + +从现在开始我们将研究对数转换的表达值。 + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战 + +可视化这种转变的另一种方法是考虑观测的尺度 +。 例如,可能值得改变轴的比例 +以便更好地在 +图的空间中分布观测值。 改变轴的比例与 +添加/修改其他组件类似(即通过逐步添加 +命令)。 尝试做这样的修改: + +- 表示 log10 尺度上未转换的表达式;参见 + `scale_x_log10()`。 将其与之前的图表进行比较。 为什么 + 现在出现警告信息? + +::::::::::::::: solution + +## 解决方案 + +```{r, eval=TRUE, purl=TRUE, echo=TRUE} +ggplot(data = rna,mapping = aes(x = expression))+ + geom_histogram() + + scale_x_log10() +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +**笔记** + +- 你在 `ggplot()` 函数中输入的任何内容都可以被你添加的任何 geom + 层看到(即,这些是全局绘图设置)。 这个 + 包括你在 `aes()` 中设置的 x 轴和 y 轴映射。 +- 您还可以独立于 `ggplot()` 函数中全局定义的 + 映射为给定的 geom 指定映射。 +- 用于添加新层的 `+` 符号必须放在包含_上一个_层的 + 行末尾。 相反,如果在包含新层的行首添加 `+` 符号 + , + `ggplot2` 将不会添加新层,并将返回错误 + 消息。 + +```{r, eval=FALSE} +# This is the correct syntax for adding layers +rna_plot + + geom_histogram() + +# This will not add the new layer and will return an error message +rna_plot + + geom_histogram() +``` + +## 迭代构建你的图 + +我们现在将绘制一个包含两个连续变量和 +`geom_point()` 函数的散点图。 该图将表示时间 8 与时间 0 以及时间 4 与时间 0 相比的表达的 log2 倍数变化 +。 +为此,我们首先需要计算基因和时间对数转换的 +表达值的平均值,然后通过 +减去时间 8 和时间 0 之间的平均对数表达值和 +减去时间 4 和时间 0 之间的平均对数表达值来计算对数倍数变化。 请注意,我们还在这里包括了基因 +生物型,我们稍后会用它来表示基因。 我们将把 +倍数变化保存在名为“rna_fc”的新数据框中。 + +```{r rna_fc, cache=FALSE, purl=TRUE} +rna_fc <- rna %>% select(gene, time, + gene_biotype, expression_log) %>% + group_by(gene, time, gene_biotype) %>% + summarize(mean_exp = mean(expression_log)) %>% + pivot_wider(names_from = time, + values_from = mean_exp) %>% + mutate(time_8_vs_0 = `8` - `0`, time_4_vs_0 = `4` - `0`) + +``` + +然后我们可以使用新创建的数据集“rna_fc”构建一个 ggplot。 +使用“ggplot2”构建图表通常是一个迭代过程。 我们 +首先定义我们将使用的数据集、布置轴,然后选择一个 +几何对象: + +```{r create-ggplot-object, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point() +``` + +然后,我们开始修改这个图以从中提取更多信息。 +例如,我们可以添加透明度(“alpha”)以避免过度绘图: + +```{r adding-transparency, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point(alpha = 0.3) +``` + +我们还可以为所有点添加颜色: + +```{r adding-colors, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point(alpha = 0.3, color = "blue") +``` + +或者为了给图中每个基因赋予不同的颜色,你可以使用一个向量作为 +参数 **color** 的输入。 `ggplot2` 将提供与向量中的不同值相对应的不同的 +颜色。 这是一个 +示例,我们用 `gene_biotype` 进行着色: + +```{r color-by-gene_biotype1, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_point(alpha = 0.3, aes(color = gene_biotype)) + +``` + +我们还可以在 +`ggplot()`函数提供的映射中直接指定颜色。 任何 geom 层都可以看到这一点,并且 +映射将由 `aes()` 中设置的 x 轴和 y 轴决定。 + +```{r color-by-gene_biotype2, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0, + color = gene_biotype)) + + geom_point(alpha = 0.3) +``` + +最后,我们还可以使用 `geom_abline()` +函数添加对角线: + +```{r adding-diag, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0, + color = gene_biotype)) + + geom_point(alpha = 0.3) + + geom_abline(intercept = 0) +``` + +请注意,我们可以将 geom 层从 `geom_point` 更改为 +`geom_jitter`,颜色仍由 `gene_biotype` 决定。 + +```{r color-by-gene_biotype3, cache=FALSE, purl=TRUE} +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0, + color = gene_biotype)) + + geom_jitter(alpha = 0.3) + + geom_abline(intercept = 0) +``` + +```{r, echo=FALSE, message=FALSE} +library("hexbin") +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战 + +散点图可以成为小数据集的有用的探索工具。 对于具有大量观测值的 +数据集,例如 `rna_fc` +数据集,点的过度绘制可能是散点图的限制。 +处理此类设置的一种策略是使用 +观测值的六边形分箱。 地块空间被镶嵌成六边形。 每个 +六边形根据其边界内的 +观测值的数量被分配一种颜色。 + +- 要在 `ggplot2` 中使用六边形分箱,首先从 CRAN 安装 R 包 + `hexbin` 并加载它。 + +- 然后使用“geom_hex()”函数生成六边形图。 + +- 与散点图相比,六边形箱 + 图的相对优势和劣势是什么? 检查上述散点图 + 并将其与您创建的六边形箱图进行比较。 + +::::::::::::::: solution + +## 解决方案 + +```{r, eval=FALSE, purl=TRUE} +install.packages("hexbin") +``` + +```{r, purl=TRUE} +library("hexbin") + +ggplot(data = rna_fc, mapping = aes(x = time_4_vs_0, y = time_8_vs_0)) + + geom_hex() + + geom_abline(intercept = 0) + +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战 + +使用你刚刚学到的知识从“rna”数据集中创建一个“expression_log” +在“sample”上的散点图,其中时间以 +不同的颜色显示。 这是显示此类数据的好方法吗? + +::::::::::::::: solution + +## 解决方案 + +```{r, eval=TRUE, purl=TRUE} +ggplot(data = rna, mapping = aes(y = expression_log, x = sample)) + + geom_point(aes(color = time)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## 箱形图 + +我们可以使用箱线图来可视化每个样本内基因表达的分布 +: + +```{r boxplot, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_boxplot() +``` + +通过向箱线图添加点,我们可以更好地了解 +测量的数量及其分布: + +```{r boxplot-with-points, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_jitter(alpha = 0.2, color = "tomato") + + geom_boxplot(alpha = 0) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战 + +请注意箱线图层是如何位于抖动图层前面的? What do +you need to change in the code to put the boxplot below the points? + +::::::::::::::: solution + +## 解决方案 + +我们应该交换这两个几何对象的顺序: + +```{r boxplot-with-points2, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_boxplot(alpha = 0) + + geom_jitter(alpha = 0.2, color = "tomato") +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +您可能会注意到 x 轴上的值仍然无法正确读取 +。 让我们改变标签的方向并垂直和水平调整它们 +以使它们不重叠。 您可以使用 +90 度角,或者试验找到适合 +对角线标签的角度: + +```{r boxplot-xaxis-rotated, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_jitter(alpha = 0.2, color = "tomato") + + geom_boxplot(alpha = 0) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战 + +根据感染的持续时间 +(“时间”),为箱线图上的数据点添加颜色。 + +\*提示:\*检查类别中的“时间”。 考虑将 +`时间`类从整数直接更改为 ggplot 映射中的因子。 为什么 +会改变 R 绘制图形的方式? + +::::::::::::::: solution + +## 解决方案 + +```{r boxplot-color-time, cache=FALSE, purl=TRUE} +# time as integer +ggplot(data = rna, + mapping = aes(y = expression_log, + x = sample)) + + geom_jitter(alpha = 0.2, aes(color = time)) + + geom_boxplot(alpha = 0) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) + +# time as factor +ggplot(data = rna, + mapping = aes(y = expression_log, + x = sample)) + + geom_jitter(alpha = 0.2, aes(color = as.factor(time))) + + geom_boxplot(alpha = 0) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战 + +箱线图是有用的摘要,但隐藏了 +分布的_形状_。 For example, if the distribution is bimodal, we would +not see it in a boxplot. 箱线图的替代方法是小提琴 +图,其中绘制了(点密度的)形状。 + +- 用小提琴图代替箱线图;参见“geom_violin()”。 使用参数“fill”根据时间在小提琴中填充 + 。 + +::::::::::::::: solution + +## 解决方案 + +```{r, eval=TRUE, echo=TRUE, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_violin(aes(fill = as.factor(time))) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战 + +- 修改小提琴图以按“性别”填充小提琴。 + +::::::::::::::: solution + +## 解决方案 + +```{r, eval=TRUE, echo=TRUE, cache=FALSE, purl=TRUE} +ggplot(data = rna, + mapping = aes(y = expression_log, x = sample)) + + geom_violin(aes(fill = sex)) + + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5)) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +## 线图 + +让我们计算一下 +感染持续时间内的平均表达量,其中 10 个基因的对数倍数变化最高,比较时间 8 与 +时间 0。 首先,我们需要选择基因并创建一个 `rna` +的子集,称为 `sub_rna`,包含 10 个选定的基因,然后我们需要对数据进行分组 +并计算每个组内的平均基因表达: + +```{r, purl=TRUE} +rna_fc <- rna_fc %>% arrange(desc(time_8_vs_0)) + +genes_selected <- rna_fc$gene[1:10] + +sub_rna <- rna %>% + filter(gene %in% genes_selected) + +mean_exp_by_time <- sub_rna %>% + group_by(gene,time) %>% + summarize(mean_exp = mean(expression_log)) + +mean_exp_by_time +``` + +我们可以绘制线图,x 轴为感染持续时间 +,y 轴为平均表达量: + +```{r first-time-series, purl=TRUE} +ggplot(data = mean_exp_by_time, mapping = aes(x = time, y = mean_exp)) + + geom_line() +``` + +不幸的是,这不起作用,因为我们将所有 +基因的数据绘制在一起。 我们需要告诉 ggplot 为每个基因画一条线,通过 +修改美学函数以包含 `group = gene`: + +```{r time-series-by-gene, purl=TRUE} +ggplot(data = mean_exp_by_time, + mapping = aes(x = time, y = mean_exp, group = gene)) + + geom_line() +``` + +如果我们添加颜色,我们将能够区分图中的基因(使用 +`color` 也会自动对数据进行分组): + +```{r time-series-with-colors, purl=TRUE} +ggplot(data = mean_exp_by_time, + mapping = aes(x = time, y = mean_exp, color = gene)) + + geom_line() +``` + +## 刻面 + +`ggplot2` 有一种称为 _faceting_ 的特殊技术,它允许用户 +根据数据集中包含的因素 +将一个图分成多个(子)图。 这些不同的子图继承了相同的属性 +(轴限制、刻度……) 以便于直接比较。 我们将 +使用它为每个基因绘制一条跨时间的线图: + +```{r first-facet, purl=TRUE} +ggplot(data = mean_exp_by_time, + mapping = aes(x = time, y = mean_exp)) + geom_line() + + facet_wrap(~ gene) +``` + +这里,所有子图的 x 轴和 y 轴具有相同的比例。 您 +可以通过修改 `scales` 来更改此默认行为,以允许 +y 轴自由缩放: + +```{r first-facet-scales, purl=TRUE} +ggplot(data = mean_exp_by_time, + mapping = aes(x = time, y = mean_exp)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") +``` + +现在我们想根据小鼠的性别来分割每个图中的线。 +为此,我们需要计算数据框 +中按“基因”、“时间”和“性别”分组的平均表达: + +```{r data-facet-by-gene-and-sex, purl=TRUE} +mean_exp_by_time_sex <- sub_rna %>% + group_by(gene, time, sex) %>% + summarize(mean_exp = mean(expression_log)) + +mean_exp_by_time_sex +``` + +我们现在可以使用 +`color`(在单个图内)按性别进一步划分来制作分面图: + +```{r facet-by-gene-and-sex, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") +``` + +通常,带有白色背景的图表在打印时看起来更易读。 我们 +可以使用函数“theme_bw()”将背景设置为白色。 +此外,我们可以删除网格: + +```{r facet-by-gene-and-sex-white-bg, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战 + +使用你刚刚学到的知识创建一个图表,描绘在 +感染持续期间,每个染色体的 +平均表达如何变化。 + +::::::::::::::: solution + +## 解决方案 + +```{r mean-exp-chromosome-time-series, purl=TRUE} +mean_exp_by_chromosome <- rna %>% + group_by(chromosome_name, time) %>% + summarize(mean_exp = mean(expression_log)) + +ggplot(data = mean_exp_by_chromosome, mapping = aes(x = time, + y = mean_exp)) + + geom_line() + + facet_wrap(~ chromosome_name, scales = "free_y") +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +`facet_wrap` 几何将图提取到任意数量的 +维度中,以使它们能够整齐地放在一页上。 另一方面, +`facet_grid` 几何允许您通过公式符号明确指定如何排列 +您的图表(`rows ~ columns`;`.` +可用作仅表示一行或一列的占位符)。 + +让我们修改之前的图来比较男性和女性的平均基因表达 +随时间的变化: + +```{r mean-exp-time-facet-sex-rows, purl=TRUE} +# One column, facet by rows +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = gene)) + + geom_line() + + facet_grid(sex ~ .) +``` + +```{r mean-exp-time-facet-sex-columns, purl=TRUE} +# One row, facet by column +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = gene)) + + geom_line() + + facet_grid(. ~ sex) +``` + +## `ggplot2` 主题 + +除了将绘图背景更改为白色的 `theme_bw()` 之外, +`ggplot2` 还附带其他几个主题,可用于快速 +更改可视化的外观。 完整的主题列表在 +处可用,网址为 [https://ggplot2.tidyverse.org/reference/ggtheme.html](https://ggplot2.tidyverse.org/reference/ggtheme.html)。 +`theme_minimal()` 和 `theme_light()` 很流行,而 `theme_void()` +可以作为创建新手工主题的起点。 + +[ggthemes](https://jrnold.github.io/ggthemes/reference/index.html) +包提供了各种各样的选项(包括 Excel 2003 +主题)。 ggplot2 提供了扩展 `ggplot2` 功能的 +软件包列表,包括额外的 +主题。 + +## 定制 + +让我们回到按时间和基因划分的平均表达的多面图, +按性别着色。 + +查看 ggplot2, +并思考如何改进图表。 + +现在,我们可以将轴的名称更改为比 +'time' 和 'mean\_exp' 更具信息量的名称,并为图形添加标题: + +```{r mean_exp-time-with-right-labels, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + labs(title = "Mean gene expression by duration of the infection", + x = "Duration of the infection (in days)", + y = "Mean gene expression") +``` + +轴具有更多信息名称,但可以通过增加字体大小来提高其可读性: + +```{r mean_exp-time-with-right-labels-xfont-size, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + labs(title = "Mean gene expression by duration of the infection", + x = "Duration of the infection (in days)", + y = "Mean gene expression") + + theme(text = element_text(size = 16)) +``` + +请注意,您也可以更改图表的字体。 如果你 +使用的是 Windows,则可能必须安装 。 + +我们可以进一步自定义 x 轴和 y 轴文本的颜色、 +网格的颜色等。 例如,我们还可以通过 +将“legend.position”设置为“top”将图例移动到顶部。 + +```{r mean_exp-time-with-theme, cache=FALSE, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + labs(title = "Mean gene expression by duration of the infection", + x = "Duration of the infection (in days)", + y = "Mean gene expression") + + theme(text = element_text(size = 16), + axis.text.x = element_text(colour = "royalblue4", size = 12), + axis.text.y = element_text(colour = "royalblue4", size = 12), + panel.grid = element_line(colour="lightsteelblue1"), + legend.position = "top") +``` + +如果您比默认主题更喜欢您所做的更改,您可以 +将它们保存为对象,以便能够轻松地将它们应用到您可能创建的其他 +图中。 下面是我们之前创建的 +直方图的一个例子。 + +```{r mean_exp-time-with-right-labels-xfont, cache=FALSE, purl=TRUE} +blue_theme <- theme(axis.text.x = element_text(colour = "royalblue4", + size = 12), + axis.text.y = element_text(colour = "royalblue4", + size = 12), + text = element_text(size = 16), + panel.grid = element_line(colour="lightsteelblue1")) + +ggplot(rna, aes(x = expression_log)) + + geom_histogram(bins = 20) + + blue_theme +``` + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战 + +掌握了所有这些信息后,请再花五分钟 +来改进本练习中生成的其中一个图表或 +创建您自己的精美图表。 使用 RStudio ggplot2 +获取灵感。 以下是一些想法: + +- 看看是否可以改变线条的粗细。 +- 你能找到办法改变传奇的名字吗? 那么 + 它的标签怎么样? (提示:寻找以 + `scale_` 开头的 ggplot 函数) +- 尝试使用不同的调色板或手动指定线条的 + 颜色(参见 + [http://www.cookbook-r.com/Graphs/Colors\_(ggplot2)/](https://www.cookbook-r.com/Graphs/Colors_\\(ggplot2\\)/))。 + +::::::::::::::: solution + +## 解决方案 + +例如,基于此图: + +```{r, purl=TRUE} +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) +``` + +我们可以通过以下方式定制它: + +```{r, purl=TRUE} +# change the thickness of the lines +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line(size=1.5) + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + +# change the name of the legend and the labels +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + scale_color_discrete(name = "Gender", labels = c("F", "M")) + +# using a different color palette +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + scale_color_brewer(name = "Gender", labels = c("F", "M"), palette = "Dark2") + +# manually specifying the colors +ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + theme_bw() + + theme(panel.grid = element_blank()) + + scale_color_manual(name = "Gender", labels = c("F", "M"), + values = c("royalblue", "deeppink")) + +``` + +::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## 创作情节 + +分面是一种很好的工具,可以将一个图分割成多个子图, +但有时您可能想要生成一个包含 +多个独立图的单个图形,即基于不同 +变量甚至不同数据框的图。 + +让我们首先创建两个想要排列在 +旁边的图: + +第一个图表计算了每个染色体上独特基因的数量。 我们 +首先需要重新排序 `chromosome_name` 的级别,并过滤每个染色体上的 +个独特基因。 我们还将 y 轴的比例更改为 +log10 比例,以提高可读性。 + +```{r sub1, purl=TRUE} +rna$chromosome_name <- factor(rna$chromosome_name, + levels = c(1:19,"X","Y")) + +count_gene_chromosome <- rna %>% select(chromosome_name, gene) %>% + distinct() %>% ggplot() + + geom_bar(aes(x = chromosome_name), fill = "seagreen", + position = "dodge", stat = "count") + + labs(y = "log10(n genes)", x = "chromosome") + + scale_y_log10() + +count_gene_chromosome +``` + +下面,我们还通过将 +`legend.position` 设置为 `"none"` 来完全删除图例。 + +```{r sub2, purl=TRUE} +exp_boxplot_sex <- ggplot(rna, aes(y=expression_log, x = as.factor(time), + color=sex)) + + geom_boxplot(alpha = 0) + + labs(y = "Mean gene exp", + x = "time") + theme(legend.position = "none") + +exp_boxplot_sex +``` + +[**patchwork**](https://github.com/thomasp85/patchwork) 包 +提供了一种优雅的方法来组合图形,使用 `+` 来 +排列图形(通常是并排)。 更具体地说,`|` +明确地将它们并排排列,而 `/` 将它们堆叠在彼此的顶部 +。 + +```{r install-patchwork, message=FALSE, eval=FALSE, purl=TRUE} +install.packages("patchwork") +``` + +```{r patchworkplot1, purl=TRUE} +library("patchwork") +count_gene_chromosome + exp_boxplot_sex +## or count_gene_chromosome | exp_boxplot_sex +``` + +```{r patchwork2, purl=TRUE} +计数基因染色体 / 指数箱线图性别 +``` + +我们可以结合 +`plot_layout` 进一步控制最终构图的布局,以创建更复杂的布局: + +```{r patchwork3, purl=TRUE} +计数基因染色体 + 指数箱线图性别 + 绘图布局(ncol = 1) +``` + +```{r patchwork4, purl=TRUE} +count_gene_chromosome + + (count_gene_chromosome + exp_boxplot_sex) + + exp_boxplot_sex + + plot_layout(ncol = 1) +``` + +最后一个图也可以使用 `|` 和 `/` 组合器来创建: + +```{r patchwork5, purl=TRUE} +count_gene_chromosome / + (count_gene_chromosome | exp_boxplot_sex) / + exp_boxplot_sex +``` + +了解有关 `patchwork` 的更多信息,请访问其 +[网页](https://patchwork.data-imaginist.com/) 或此 +[视频](https://www.youtube.com/watch?v=0m4yywqNPVY)。 + +另一个选项是 **`gridExtra`** 包,它允许使用 `grid.arrange()` 将 +个单独的 ggplots 组合成一个图形: + +```{r install-gridextra, message=FALSE, eval=FALSE, purl=TRUE} +安装.包(“gridExtra”) +``` + +```{r gridarrange-example, message=FALSE, fig.width=10, purl=TRUE} +library("gridExtra") +grid.arrange(count_gene_chromosome, exp_boxplot_sex, ncol = 2) +``` + +除了用于进行简单 +排列的 `ncol` 和 `nrow` 参数之外,还有用于 构建更复杂的 +布局 的工具。 + +## 导出地块 + +创建图表后,您可以将其保存为您喜欢的 +格式的文件。 RStudio 中 **Plot** 窗格中的“导出”选项卡将以低分辨率保存您的 +图,这种图不会被许多期刊接受,并且 +不适合作为海报缩放。 + +相反,使用 `ggsave()` 函数,它允许您通过调整适当的 +参数(`width`、`height` 和 `dpi`)轻松更改图的 +维度和分辨率。 + +确保你的工作目录中有“fig_output/”文件夹。 + +```{r ggsave-example, eval=FALSE, purl=TRUE} +my_plot <- ggplot(data = mean_exp_by_time_sex, + mapping = aes(x = time, y = mean_exp, color = sex)) + + geom_line() + + facet_wrap(~ gene, scales = "free_y") + + labs(title = "Mean gene expression by duration of the infection", + x = "Duration of the infection (in days)", + y = "Mean gene expression") + + guides(color=guide_legend(title="Gender")) + + theme_bw() + + theme(axis.text.x = element_text(colour = "royalblue4", size = 12), + axis.text.y = element_text(colour = "royalblue4", size = 12), + text = element_text(size = 16), + panel.grid = element_line(colour="lightsteelblue1"), + legend.position = "top") +ggsave("fig_output/mean_exp_by_time_sex.png", my_plot, width = 15, + height = 10) + +# This also works for grid.arrange() plots +combo_plot <- grid.arrange(count_gene_chromosome, exp_boxplot_sex, + ncol = 2, widths = c(4, 6)) +ggsave("fig_output/combo_plot_chromosome_sex.png", combo_plot, + width = 10, dpi = 300) +``` + +注意:参数“width”和“height”也决定了保存的图中的字体大小 +。 + +```{r final-challenge, eval=FALSE, purl=TRUE, echo=FALSE} +### 最终绘图挑战: +## 掌握所有这些信息后,请再花五 +## 分钟来改进此 +## 练习中生成的图表之一,或创建您自己的精美图表。使用 RStudio +## ggplot2 备忘单获取灵感: +## https://raw.githubusercontent.com/rstudio/cheatsheets/main/data-visualization.pdf +``` + +## 其他可视化包 + +`ggplot2` 是一个非常强大的包,非常适合我们的 _tidy +数据_ 和 _tidy 工具_ 管道。 R 中还有其他可视化包 +不容忽视。 + +### 基础图形 + +R 自带的默认图形系统通常称为 _base R +graphics_ ,简单而快速。 它基于_画家或画布 +模型_,其中不同的输出直接叠加在每个 +其他输出之上(参见图@ref(fig:paintermodel))。 这是与 `ggplot2`(以及下面描述的 `lattice`)的一个根本的 +区别,即 +返回在屏幕或文件中呈现的专用对象,以及 +甚至可以更新。 + +```{r paintermodel, fig.width=12, fig.height=4, fig.cap="Successive layers added on top of each other."} +par(mfrow = c(1, 3)) +plot(1:20, main = "First layer, produced with plot(1:20)") + +plot(1:20, main = "A horizontal red line, added with abline(h = 10)") +abline(h = 10, col = "red") + +plot(1:20, main = "A rectangle, added with rect(5, 5, 15, 15)") +abline(h = 10, col = "red") +rect(5, 5, 15, 15, lwd = 3) +``` + +另一个主要区别是,基本图形的绘图功能会尝试根据其输入类型 +做_正确_的事情,即,它们将根据其输入的类别调整 +其行为。 这与我们在 `ggplot2` 中所用的又非常 +不同,它仅接受数据框 +作为输入,并且需要一点一点地构建图表。 + +```{r plotmethod, fig.width=8, fig.height=8, fig.cap="Plotting boxplots (top) and histograms (bottom) vectors (left) or a matrices (right)."} +par(mfrow = c(2, 2)) +boxplot(rnorm(100), + main = "Boxplot of rnorm(100)") +boxplot(matrix(rnorm(100), ncol = 10), + main = "Boxplot of matrix(rnorm(100), ncol = 10)") +hist(rnorm(100)) +hist(matrix(rnorm(100), ncol = 10)) +``` + +基础图形中的开箱即用方法对于 +简单标准图形非常有效,可以使用 +单行代码和一个函数(例如`plot`,`hist`,或 +`boxplot`)非常快速地生成... 然而,默认值并不总是最吸引人的 +,并且图形的调整,尤其是当它们变得更加复杂时(例如 +产生方面),可能会变得冗长而繁琐。 + +### lattice 包 + +**`lattice`** 包与 `ggplot2` 类似,它使用 +数据框作为输入,返回图形对象并支持分面。 +`lattice` however isn't based on the grammar of graphics and has a more +convoluted interface. + +`lattice` 包的一个很好的参考是@latticebook。 + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- R 中的可视化 + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/zh/episodes/60-next-steps.Rmd b/locale/zh/episodes/60-next-steps.Rmd new file mode 100644 index 000000000..e004a933c --- /dev/null +++ b/locale/zh/episodes/60-next-steps.Rmd @@ -0,0 +1,464 @@ +--- +source: 放射科 +title: 下一步 +teaching: 四十五 +exercises: 四十五 +--- + +```{r, include=FALSE} +``` + +::::::::::::::::::::::::::::::::::::::: objectives + +- 介绍Bioconductor项目。 +- 引入数据容器的概念。 +- 概述在 + 组学分析中广泛使用的`SummarizedExperiment`。 + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::: questions + +- 什么是“SummarizedExperiment”? +- 什么是 Bioconductor? + +::::::::::::::::::::::::::::::::::::::::::::::::::::: + +## 下一步 + +```{r, echo=FALSE, message=FALSE} +library("tidyverse") +``` + +生物信息学中的数据通常很复杂。 为了解决这个问题, +开发人员定义了专门的数据容器(称为类), +与他们需要处理的数据的属性相匹配。 + +这一方面是 **Bioconductor**[^Bioconductor] 项目 +的核心,它在各个包中使用相同的 **核心数据基础设施**。 这 +无疑为 Bioconductor 的成功做出了贡献。 Bioconductor package +developers are advised to make use of existing infrastructure to +provide coherence, interoperability, and stability to the project as a +whole. + +[^Bioconductor]: The [Bioconductor](https://www.bioconductor.org) was + initiated by Robert Gentleman, one of the two creators of the R + language. Bioconductor 提供专用于组学数据 + 分析的工具。 Bioconductor 使用 R 统计编程语言 + ,并且是开源和开放开发的。 + +为了说明这样的组学数据容器,我们将介绍 +`SummarizedExperiment`类。 + +## 总结实验 + +下图显示了 SummarizedExperiment 类的结构。 + +```{r SE, echo=FALSE, out.width="80%"} +knitr::include_graphics("https://uclouvain-cbio.github.io/WSBIM1322/figs/SE.svg") +``` + +SummarizedExperiment 类的对象包含: + +- **一个(或多个)分析**包含定量组学数据 + (表达数据),存储为类似矩阵的对象。 特征(基因、 + 转录本、蛋白质……) 沿着行定义,并沿着列采样 + 。 + +- 包含样本协变量的**样本元数据**槽,存储为 + 数据框。 该表中的行代表样本(行与表达数据的 + 列完全匹配)。 + +- 包含特征协变量的**特征元数据**槽,存储为 + 数据框。 该数据框的行与 + 表达数据的行完全匹配。 + +`SummarizedExperiment` 的协调特性保证了在数据操作过程中 +不同插槽的维度将 +始终匹配(即表达数据中的列,然后是 +样本元数据中的行,以及表达数据和 +特征元数据中的行)。 例如,如果我们必须 +从检测中排除一个样本,那么它将在同一操作中自动从样本元数据中删除 +。 + +元数据槽可以增加额外的协变量 +(列)而不会影响其他结构。 + +### 创建汇总实验 + +为了创建一个`SummarizedExperiment`,我们将从 csv 文件中创建 +个单独组件,即计数矩阵、样本和基因 +元数据。 这些通常是 RNA-Seq 数据 +的提供方式(在原始数据被处理之后)。 + +```{r, echo=FALSE, message=FALSE} +rna <- read_csv("data/rnaseq.csv") + +## count matrix +counts <- rna %>% + select(gene, sample, expression) %>% + pivot_wider(names_from = sample, + values_from = expression) + +## convert to matrix and set row names +count_matrix <- counts %>% select(-gene) %>% as.matrix() +rownames(count_matrix) <- counts$gene + +## sample annotation +sample_metadata <- rna %>% + select(sample, organism, age, sex, infection, strain, time, tissue, mouse) + +## remove redundancy +sample_metadata <- unique(sample_metadata) + +## gene annotation +gene_metadata <- rna %>% + select(gene, ENTREZID, product, ensembl_gene_id, external_synonym, + chromosome_name, gene_biotype, phenotype_description, + hsapiens_homolog_associated_gene_name) + +# remove redundancy +gene_metadata <- unique(gene_metadata) + +## write to csv +write.csv(count_matrix, file = "data/count_matrix.csv") +write.csv(gene_metadata, file = "data/gene_metadata.csv", row.names = FALSE) +write.csv(sample_metadata, file = "data/sample_metadata.csv", row.names = FALSE) +``` + +- **表达矩阵**:我们加载计数矩阵,指定 + 第一列包含行/基因名称,并将 + `data.frame`转换为`matrix`。 您可以从 [这里](https://carpentries-incubator.github.io/bioc-intro/data/count_matrix.csv) 下载它 + 。 + +```{r} +count_matrix <- read.csv("data/count_matrix.csv", + row.names = 1) %>% + as.matrix() + +count_matrix[1:5, ] +dim(count_matrix) +``` + +- **描述样本的表格**,可在 + [此处](https://carpentries-incubator.github.io/bioc-intro/data/sample_metadata.csv) 获取。 + +```{r} +sample_metadata <- read.csv("data/sample_metadata.csv") +sample_metadata +dim(sample_metadata) +``` + +- **描述基因的表格**,可在 + [此处](https://carpentries-incubator.github.io/bioc-intro/data/gene_metadata.csv) 获取。 + +```{r} +gene_metadata <- read.csv("data/gene_metadata.csv") +gene_metadata[1:10, 1:4] +dim(gene_metadata) +``` + +我们将根据以下表格创建一个“SummarizedExperiment”: + +- 将用作\*\*\`分析\*\*的计数矩阵 + +- 描述样本的表格将用作**样本 + 元数据**槽 + +- 描述基因的表格将用作**特征 + 元数据**槽 + +为此,我们可以使用 +`SummarizedExperiment` 构造函数将不同的部分放在一起: + +```{r, message=FALSE, warning=FALSE} +## BiocManager::install("SummarizedExperiment") +library("SummarizedExperiment") +``` + +首先,我们确保 +计数矩阵和样本注释中的样本顺序相同,并且 +计数矩阵和基因注释中的基因顺序相同。 + +```{r} +stopifnot(rownames(count_matrix) == gene_metadata$gene) +stopifnot(colnames(count_matrix) == sample_metadata$sample) +``` + +```{r} +se <- SummarizedExperiment(assays = list(counts = count_matrix), + colData = sample_metadata, + rowData = gene_metadata) +se +``` + +### 保存数据 + +就像我们在上一集中所做的那样,将数据导出到电子表格有 +几个限制,例如第一章 +中描述的限制(小数分隔符 `,` 和 `.` 可能不一致,以及 +缺少变量类型定义)。 此外,将数据导出到 +电子表格仅与矩形数据(例如数据框 +和矩阵)相关。 + +保存数据的更通用的方法是使用 `saveRDS` +函数,这种方法特定于 R,并且 +保证可以在任何操作系统上运行。 像这样保存对象将在磁盘上生成二进制 +表示(此处使用`rds`文件扩展名),可以使用`readRDS`函数将其 +加载回R。 + +```{r, eval=FALSE} +saveRDS(se,file = “data_output/se.rds”) +rm(se) +se <- readRDS(“data_output/se.rds”) +head(se) +``` + +To conclude, when it comes to saving data from R that will be loaded +again in R, saving and loading with `saveRDS` and `readRDS` is the +preferred approach. 如果需要与不使用 R 的人 +共享表格数据,那么导出到基于文本的电子表格是一个 +不错的选择。 + +使用这个数据结构,我们可以通过 +`assay` 函数访问表达矩阵: + +```{r} +head(assay(se)) +dim(assay(se)) +``` + +我们可以使用“colData”函数访问样本元数据: + +```{r} +colData(se) +dim(colData(se)) +``` + +我们还可以使用“rowData”函数访问特征元数据: + +```{r} +head(rowData(se)) +dim(rowData(se)) +``` + +### 对 SummarizedExperiment 进行子集设置 + +SummarizedExperiment 可以像数据框一样被子集化,具有 +数字或逻辑字符。 + +下面,我们创建 SummarizedExperiment 类的新实例,其中 +仅包含前 3 个样本的前 5 个特征。 + +```{r} +se1 <- se[1:5, 1:3] +se1 +``` + +```{r} +colData(se1) +rowData(se1) +``` + +我们还可以使用 `colData()` 函数从 +样本元数据中对某些内容进行子集化,或者使用 `rowData()` 从 +特征元数据中对某些内容进行子集化。 例如,这里我们只保留 miRNA 和非 +感染的样本: + +```{r} +se1 <- se[rowData(se)$gene_biotype == "miRNA", + colData(se)$infection == "NonInfected"] +se1 +assay(se1) +colData(se1) +rowData(se1) +``` + + + + + + + + + + + + + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战 + +提取时间 0 和时间 8 时样本 +中前 3 个基因的基因表达水平。 + +::::::::::::::: solution + +## 解决方案 + +```{r, purl=FALSE} +assay(se)[1:3, colData(se)$time != 4] + +# Equivalent to +assay(se)[1:3, colData(se)$time == 0 | colData(se)$time == 8] +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::: challenge + +## 挑战 + +验证您是否使用长“rna”表获得相同的值。 + +::::::::::::::: solution + +## 解决方案 + +```{r, purl=FALSE} +rna |> + filter(gene %in% c("Asl", "Apod", "Cyd2d22")) |> + filter(time != 4) |> select(expression) +``` + +::::::::::::::::::::::::: + +:::::::::::::::::::::::::::::::::::::::::::::::::: + +长表和`SummarizedExperiment`包含相同的 +信息,但是结构不同。 每种方法都有其 +自身的优势:前者非常适合`tidyverse`包, +而后者是许多生物信息学和 +统计处理步骤的首选结构。 例如,典型的 RNA-Seq 分析使用 +`DESeq2` 包。 + +#### 向元数据添加变量 + +我们还可以向元数据中添加信息。 +假设您想添加收集样本的中心…… + +```{r} +colData(se)$center <- rep("University of Illinois", nrow(colData(se))) +colData(se) +``` + +This illustrates that the metadata slots can grow indefinitely without +affecting the other structures! + +### tidy总结实验 + +您可能想知道,我们可以使用 tidyverse 命令与 +`SummarizedExperiment` 对象交互吗? 答案是肯定的,我们可以使用 +`tidySummarizedExperiment` 包。 + +记住我们的 SummarizedExperiment 对象是什么样的: + +```{r, message=FALSE} +se +``` + +加载“tidySummarizedExperiment”,然后再次查看 se 对象 +。 + +```{r, message=FALSE} +#BiocManager::install("tidySummarizedExperiment") +library("tidySummarizedExperiment") + +se +``` + +它仍然是一个 `SummarizedExperiment` 对象,因此保持了高效的 +结构,但现在我们可以将其视为一个 tibble。 注意输出的第一行 +说明了这一点,它是一个 `SummarizedExperiment`\-`tibble` +抽象。 我们还可以在输出的第二行看到 +份成绩单和样本的数量。 + +如果我们想恢复到标准的“SummarizedExperiment”视图,我们 +可以这样做。 + +```{r} +options("restore_SummarizedExperiment_show" = TRUE) +se +``` + +但这里我们使用 tibble 视图。 + +```{r} +options("restore_SummarizedExperiment_show" = FALSE) +se +``` + +我们现在可以使用 tidyverse 命令与 +`SummarizedExperiment` 对象交互。 + +我们可以使用“过滤器”根据条件过滤行,例如查看 +一个样本的所有行。 + +```{r} +se %>% filter(.sample == "GSM2545336") +``` + +我们可以使用“select”来指定我们想要查看的列。 + +```{r} +se %>% select(.sample) +``` + +我们可以使用“mutate”来添加元数据信息。 + +```{r} +se %>% mutate(center = "Heidelberg University") +``` + +我们还可以将命令与 tidyverse 管道“%>%”组合起来。 对于 +示例,我们可以结合 `group_by` 和 `summarise` 来获取每个样本的总 +计数。 + +```{r} +se %>% + group_by(.sample) %>% + summarise(total_counts=sum(counts)) +``` + +我们可以将整洁的 SummarizedExperiment 对象视为用于绘图的正常 tibble +。 + +这里我们绘制了每个样本的计数分布。 + +```{r tidySE-plot} +se %>% + ggplot(aes(counts + 1, group=.sample, color=infection)) + + geom_density() + + scale_x_log10() + + theme_bw() +``` + +有关 tidySummarizedExperiment 的更多信息,请参阅包 +网站 +[此处](https://stemangiola.github.io/tidySummarizedExperiment/)。 + +**带回家的信息** + +- `SummarizedExperiment` 代表了一种存储和 + 处理组学数据的有效方法。 + +- 它们被用于许多 Bioconductor 包中。 + +如果您参加下一次以 RNA 测序分析为重点的培训, +您将学习使用 Bioconductor `DESeq2` 包进行一些 +差异表达分析。 `DESeq2` +包的整个分析在 `SummarizedExperiment` 中处理。 + +:::::::::::::::::::::::::::::::::::::::: keypoints + +- Bioconductor 是一个为 + 理解高通量生物学数据提供支持和包的项目。 +- A `SummarizedExperiment2` is a type of object useful to store and + manage high-throughput omics data. + +:::::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/locale/zh/index.md b/locale/zh/index.md new file mode 100644 index 000000000..f6e3116fd --- /dev/null +++ b/locale/zh/index.md @@ -0,0 +1,18 @@ +--- +permalink: index.html +site: sandpaper::sandpaper_site +--- + +## About this course + +:::::::::::::::::::::::::::::::::::::::::: prereq + +## Prerequisites + +- Familiarity with tabular data and spreadsheets. + +:::::::::::::::::::::::::::::::::::::::::::::::::: + + + + diff --git a/locale/zh/instructors/instructor-notes.md b/locale/zh/instructors/instructor-notes.md new file mode 100644 index 000000000..cec65daca --- /dev/null +++ b/locale/zh/instructors/instructor-notes.md @@ -0,0 +1,9 @@ +--- +title: Instructor Notes +--- + +FIXME + + + + diff --git a/locale/zh/learners/discuss.md b/locale/zh/learners/discuss.md new file mode 100644 index 000000000..515e3baf1 --- /dev/null +++ b/locale/zh/learners/discuss.md @@ -0,0 +1,9 @@ +--- +title: Discussion +--- + +FIXME + + + + diff --git a/locale/zh/learners/reference.md b/locale/zh/learners/reference.md new file mode 100644 index 000000000..3466d35cf --- /dev/null +++ b/locale/zh/learners/reference.md @@ -0,0 +1,11 @@ +--- +{} +--- + +## Glossary + +FIXME + + + + diff --git a/locale/zh/learners/setup.md b/locale/zh/learners/setup.md new file mode 100644 index 000000000..2c33990f5 --- /dev/null +++ b/locale/zh/learners/setup.md @@ -0,0 +1,158 @@ +--- +title: Setup +--- + +- Please make sure you have a spreadsheet editor at hand, such as + LibreOffice, Microsoft Excel or Google Sheets. + +- Install R, RStudio and packages (see below). + +### R and RStudio + +- R and RStudio are separate downloads and installations. R is the + underlying statistical computing environment, but using R alone is + no fun. RStudio is a graphical integrated development environment + (IDE) that makes using R much easier and more interactive. You need + to install R before you install RStudio. After installing both + programs, you will need to install some specific R packages within + RStudio. Follow the instructions below for your operating system, + and then follow the instructions to install packages. + +### You are running Windows + +
+ +::::::::::::::: solution + +## If you already have R and RStudio installed + +- Open RStudio, and click on "Help" > "Check for updates". If a new version is + available, quit RStudio, and download the latest version for RStudio. + +- To check which version of R you are using, start RStudio and the first thing + that appears in the console indicates the version of R you are + running. Alternatively, you can type `sessionInfo()`, which will also display + which version of R you are running. Go on + the [CRAN website](https://cran.r-project.org/bin/windows/base/) and check + whether a more recent version is available. If so, please download and install + it. You can [check here](https://cran.r-project.org/bin/windows/base/rw-FAQ.html#How-do-I-UNinstall-R_003f) for + more information on how to remove old versions from your system if you wish to do so. + +- Follow the steps in the instructions [for everyone](#for-everyone) at the + bottom of this page. + +::::::::::::::::::::::::: + +::::::::::::::: solution + +## If you don't have R and RStudio installed + +- Download R from + the [CRAN website](https://cran.r-project.org/bin/windows/base/release.htm). + +- Run the `.exe` file that was just downloaded + +- Go to the [RStudio download page](https://www.rstudio.com/products/rstudio/download/#download) + +- Under _All Installers_ select **RStudio xxxx.yy.zz-uuu.exe - Windows 10/11** (where x, y, z, and u represent version numbers) + +- Double click the file to install it + +- Once it's installed, open RStudio to make sure it works and you don't get any + error messages + +- Follow the steps in the instructions [for everyone](#for-everyone) at the + bottom of this page. + +::::::::::::::::::::::::: + +### You are running macOS + +
+ +::::::::::::::: solution + +## If you already have R and RStudio installed + +- Open RStudio, and click on "Help" > "Check for updates". If a new version is + available, quit RStudio, and download the latest version for RStudio. + +- To check the version of R you are using, start RStudio and the first thing + that appears on the terminal indicates the version of R you are running. Alternatively, you can type `sessionInfo()`, which will + also display which version of R you are running. Go on + the [CRAN website](https://cran.r-project.org/bin/macosx/) and check + whether a more recent version is available. If so, please download and install + it. + +- Follow the steps in the instructions [for everyone](#for-everyone) at the + bottom of this page. + +::::::::::::::::::::::::: + +::::::::::::::: solution + +## If you don't have R and RStudio installed + +- Download R from + the [CRAN website](https://cran.r-project.org/bin/macosx/). + +- Select the `.pkg` file for the latest R version + +- Double click on the downloaded file to install R + +- It is also a good idea to install [XQuartz](https://www.xquartz.org/) (needed + by some packages) + +- Go to the [RStudio download page](https://www.rstudio.com/products/rstudio/download/#download) + +- Under _All Installers_ select **RStudio xxxx.yy.zz-uuu.dmg - macOS 10.15+** (where x, y, z, and u represent version numbers) + +- Double click the file to install RStudio + +- Once it's installed, open RStudio to make sure it works and you don't get any + error messages. + +- Follow the steps in the instructions [for everyone](#for-everyone) at the + bottom of this page. + +::::::::::::::::::::::::: + +### You are running Linux + +
+ +::::::::::::::: solution + +## Install R using your package manager and RStudio + +- Follow the instructions for your distribution + from [CRAN](https://cloud.r-project.org/bin/linux), they provide information + to get the most recent version of R for common distributions. For most + distributions, you could use your package manager (e.g., for Debian/Ubuntu run + `sudo apt-get install r-base`, and for Fedora `sudo yum install R`), but we + don't recommend this approach as the versions provided by this are + usually out of date. In any case, make sure you have at least R 4.2.0. +- Go to the RStudio download + page +- Under _All Installers_ select the version that matches your distribution, and + install it with your preferred method (e.g., with Debian/Ubuntu `sudo dpkg -i rstudio-xxxx.yy.zz-uuu-amd64.deb` at the terminal). +- Once it's installed, open RStudio to make sure it works and you don't get any + error messages. +- Follow the steps in the [instructions for everyone](#for-everyone) + +::::::::::::::::::::::::: + +### For everyone + +After installing R and RStudio, you need to install a couple of +packages that will be used during the workshop. We will also learn +about package installation during the course to explain the following +commands. For now, simply follow the instructions below: + +- Start RStudio by double-clicking the icon and then type: + +```r +install.packages(c("BiocManager", "remotes")) +BiocManager::install(c("tidyverse", "SummarizedExperiment", "hexbin", + "patchwork", "gridExtra", "lubridate")) +``` diff --git a/locale/zh/profiles/learner-profiles.md b/locale/zh/profiles/learner-profiles.md new file mode 100644 index 000000000..75b2c5cad --- /dev/null +++ b/locale/zh/profiles/learner-profiles.md @@ -0,0 +1,5 @@ +--- +title: FIXME +--- + +This is a placeholder file. Please add content here.