{"id":5,"date":"2018-05-22T11:35:58","date_gmt":"2018-05-22T09:35:58","guid":{"rendered":"http:\/\/mon.uvic.cat\/statistical-pills\/?page_id=5"},"modified":"2021-10-04T18:40:37","modified_gmt":"2021-10-04T16:40:37","slug":"introduction-to-r","status":"publish","type":"page","link":"https:\/\/mon.uvic.cat\/statistical-pills\/introduction-to-r\/","title":{"rendered":"Introduction to R"},"content":{"rendered":"<div id=\"toc\">\n<div id=\"toc_header\"><strong>Table of Contents\u00a0\u00a0 <a href=\"http:\/\/mon.uvic.cat\/statistical-pills\/files\/2021\/02\/FCT.png\"><img loading=\"lazy\" decoding=\"async\" class=\"size-medium wp-image-687 alignright\" src=\"http:\/\/mon.uvic.cat\/statistical-pills\/files\/2021\/02\/FCT-300x58.png\" alt=\"\" width=\"300\" height=\"58\" srcset=\"https:\/\/mon.uvic.cat\/statistical-pills\/files\/2021\/02\/FCT-300x58.png 300w, https:\/\/mon.uvic.cat\/statistical-pills\/files\/2021\/02\/FCT-1024x199.png 1024w, https:\/\/mon.uvic.cat\/statistical-pills\/files\/2021\/02\/FCT-768x150.png 768w, https:\/\/mon.uvic.cat\/statistical-pills\/files\/2021\/02\/FCT-1536x299.png 1536w, https:\/\/mon.uvic.cat\/statistical-pills\/files\/2021\/02\/FCT.png 1623w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><br \/>\n<\/strong><\/div>\n<ul>\n<li>\n<h5><a href=\"#toc_0\">Installation: R and Rstudio<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_1\">Using scripts<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_2\">Simple computations with R<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_3\">R functions<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_4\">Help and documentation<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_5\">List and remove objects<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_6\">Working directory<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_7\">Data structures<\/a><\/h5>\n<ul>\n<li>\n<h5><a href=\"#toc_8\">Vector<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_11\">Matrix<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_16\">Data frame<\/a><\/h5>\n<ul>\n<li>\n<h5><a href=\"#toc_20\">Subsetting<\/a><\/h5>\n<\/li>\n<\/ul>\n<\/li>\n<li>\n<h5><a href=\"#toc_21\">List<\/a><\/h5>\n<\/li>\n<\/ul>\n<\/li>\n<li>\n<h5><a href=\"#toc_26\">Data types and factor variables<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_29\">Reading and writing data files<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_33\">Libraries and packages<\/a><\/h5>\n<ul>\n<li>\n<h5><a href=\"#toc_34\">Libraries\/Packages<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_35\">Install packages from CRAN<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_36\">Install packages from Bioconductor<\/a><\/h5>\n<\/li>\n<\/ul>\n<\/li>\n<li>\n<h5><a href=\"#toc_37\">Basic statistical functions<\/a><\/h5>\n<ul>\n<li>\n<h5><a href=\"#toc_38\">Summary statistics<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_42\">Test statistics<\/a><\/h5>\n<ul>\n<li>\n<h5><a href=\"#toc_43\">t-test for the equality of two means from independent samples<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_44\">F test for the equality of two variances<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_45\">Wilcoxon test for the equality of two means from independent samples<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_46\">t.test for paired samples<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_47\">Wilcoxon test for paired samples<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_48\">One-factor ANOVA for testing the equality of more than two means<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_49\">Kruskal-Wallis test for testing the equality of more than two means<\/a><\/h5>\n<\/li>\n<\/ul>\n<\/li>\n<li>\n<h5><a href=\"#toc_50\">Regression models<\/a><\/h5>\n<ul>\n<li>\n<h5><a href=\"#toc_51\">linear regression<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_52\">logistic regression<\/a><\/h5>\n<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<li>\n<h5><a href=\"#toc_53\">Graphs with R<\/a><\/h5>\n<ul>\n<li>\n<h5><a href=\"#toc_54\">Principal graphical representations<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_55\">Saving plots to a file<\/a><\/h5>\n<\/li>\n<\/ul>\n<\/li>\n<li>\n<h5><a href=\"#toc_56\">Programming with R<\/a><\/h5>\n<ul>\n<li>\n<h5><a href=\"#toc_57\">Functions with R<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_58\">Programming tools: if-else statement<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_59\">Programming tools: for-loop<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_60\">Avoid loops whenever possible<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_61\">Useful functions to avoid loops<\/a><\/h5>\n<ul>\n<li>\n<h5><a href=\"#toc_62\">Function apply()<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_63\">Function tapply()<\/a><\/h5>\n<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<li>\n<h5><a href=\"#toc_64\">Data management with R<\/a><\/h5>\n<ul>\n<li>\n<h5><a href=\"#toc_65\">Modifying the elements of a numeric or character variable<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_66\">Modifying elements of a factor variable<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_67\">Modifying the column names<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_68\">Adding and removing columns of a data frame<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_69\">Sorting elements<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_70\">Missing values<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_71\">Manipulating strings<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_72\">Data type conversion<\/a><\/h5>\n<\/li>\n<\/ul>\n<\/li>\n<li>\n<h5><a href=\"#toc_73\">Workspace<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_74\">Miscellaneous. Useful functions<\/a><\/h5>\n<ul>\n<li>\n<h5><a href=\"#toc_75\">Function source()<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_76\">Function with()<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_77\">Function which()<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_78\">Function list.files()<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_79\">Function sessionInfo()<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_80\">The stringsAsFactors and as.is arguments<\/a><\/h5>\n<\/li>\n<li>\n<h5><a href=\"#toc_81\">attach() and detach()<\/a><\/h5>\n<\/li>\n<\/ul>\n<\/li>\n<li>\n<h5><a href=\"#toc_82\">Documentation<\/a><\/h5>\n<\/li>\n<\/ul>\n<\/div>\n<p><a href=\"http:\/\/mon.uvic.cat\/statistical-pills\/files\/2018\/06\/Exercises-Introduction-to-R.pdf\"><strong>\u261e\u00a0\u00a0 Proposed exercises<\/strong><\/a><\/p>\n<h2 id=\"toc_0\">Installation: R and Rstudio<\/h2>\n<p>R is a free software language and environment for statistical analyses.<\/p>\n<p>\u261e Install R from <a href=\"http:\/\/cran.r-project.org\">http:\/\/cran.r-project.org<\/a> and choose one of these options:<\/p>\n<ul>\n<li>Download R for Linux<\/li>\n<li>Download R for (Mac) OS X<\/li>\n<li>Download R for Windows<\/li>\n<\/ul>\n<p>When the installation is finished, you should see an \u201cR\u201d icon on your desktop.<br \/>\nClicking on this icon opens the standard R interface. However, we recommend the use of the RStudio interface:<\/p>\n<p>\u261e Install Rstudio from <a href=\"http:\/\/www.rstudio.org\/\">http:\/\/www.rstudio.org\/<\/a><\/p>\n<p>The usual Rstudio screen has four windows.<\/p>\n<ol>\n<li>Console (bottom left)<\/li>\n<li>Editor or script window (top left)<\/li>\n<li>Workspace and history (top right)<\/li>\n<li>Files, plots, packages and help (bottom right)<\/li>\n<\/ol>\n<p>The first time that you use Rstudio only windows 1, 3 and 4 are shown. To open<br \/>\nwindow 2 you should open or create a new <strong>script file<\/strong>: <em>File -&gt; New -&gt; R Script<\/em><\/p>\n<p>You can type commands in the <strong>console window<\/strong> after the prompt (&gt;) and press ENTER to execute the command line. The output will appear immediately below<br \/>\nthe command line in the command window.<\/p>\n<p>However, it is usually more convenient to use R scripts and type commands in the <strong>editor window<\/strong><br \/>\n(See below section \u201cUsing<br \/>\nscripts\u201d)<\/p>\n<p>\u261e Read Section 2.3 \u201cRstudio layout\u201d from document <a href=\"http:\/\/cran.r-project.org\/doc\/contrib\/Torfs+Brauer-Short-R-Intro.pdf\">\u201cA (very) short introduction to R\u201d<\/a> by P. Torfs and C. Brauer<\/p>\n<h2 id=\"toc_1\">Using scripts<\/h2>\n<p>An R script is a text file where you type the commands that you want to execute. The R script is where you keep a record of your work. Using R scripts is very convenient because all R commands used in a session are saved in the script file and can be executed again in a future session. Script files have extension .R, for instance, \u201cmyscript.R\u201d.<\/p>\n<p>To create a new R script go to<\/p>\n<p><em>File -&gt; New -&gt; R Script<\/em><\/p>\n<p>To open an existing R script go to<\/p>\n<p><em>File -&gt; Open -&gt; R Script-&gt;select your script<\/em><\/p>\n<p>If you want to run a line from the script window, you place the cursor in any place of the line and click <em>Run<\/em> or press <em>CTRL+ENTER<\/em> if you are using Windows\/Linux or <em>Command+Enter<\/em> if you are using MAC.<\/p>\n<p>You can execute part of a script (or the whole script) by selecting the corresponding lines and pressing <em>Run<\/em> or<br \/>\n<em>CTRL+ENTER<\/em> or <em>Command+Enter<\/em>.<\/p>\n<p>\u261e Read Section 5 \u201cScripts\u201d from document <a href=\"http:\/\/cran.r-project.org\/doc\/contrib\/Torfs+Brauer-Short-R-Intro.pdf\">\u201cA (very) short introduction to R\u201d<\/a><br \/>\nby P. Torfs and C. Brauer<\/p>\n<h2 id=\"toc_2\">Simple computations with R<\/h2>\n<p>R can be used as a calculator. You can just type your equation and execute the<br \/>\ncommand:<\/p>\n<p><strong>Example:<\/strong> Addition of two values<\/p>\n<pre><code class=\"r\">3 + 6\r\n<\/code><\/pre>\n<pre>## [1] 9\r\n<\/pre>\n<pre># The output is always preceded by a number between brackets: [1]\r\n<\/pre>\n<p>Calculating the perimeter of the circumference with radius 3<\/p>\n<pre><code class=\"r\">2 * 3.1416 * 3\r\n<\/code><\/pre>\n<pre>## [1] 18.8496\r\n<\/pre>\n<p><strong>Variables<\/strong><\/p>\n<p>You can assign a number to a name with the backward arrow <code>&lt;-<\/code>:<\/p>\n<pre><code class=\"r\">x &lt;- 3\r\n<\/code><\/pre>\n<p>Now \u201cx\u201d is called a variable and it appears in the <strong>workspace window<\/strong>, which means<br \/>\nthat R stores the value of \u201cx\u201d in its memory and it can be used later.<\/p>\n<p>In general, by using the backward arrow <code>&lt;-<\/code> , you can assign a value to an object.<\/p>\n<p>If you type the name of a variable, the current value of the variable will be printed<\/p>\n<pre><code class=\"r\">x\r\n<\/code><\/pre>\n<pre>## [1] 3\r\n<\/pre>\n<p>There are variables that are already defined in R, like variable \u201cpi\u201d<\/p>\n<pre><code class=\"r\">pi\r\n<\/code><\/pre>\n<pre>## [1] 3.141593\r\n<\/pre>\n<p>Calculating the perimeter of the circumference with radius 3<\/p>\n<pre><code class=\"r\">2 * pi * x\r\n<\/code><\/pre>\n<pre>## [1] 18.84956\r\n<\/pre>\n<p>Changing the value of radius and reusing the code<\/p>\n<pre><code class=\"r\">x &lt;- 5\r\n2 * pi * x\r\n<\/code><\/pre>\n<pre>## [1] 31.41593\r\n<\/pre>\n<p><strong>Remarks<\/strong><\/p>\n<ol>\n<li>R is case sensitive<\/li>\n<\/ol>\n<pre><code class=\"r\">A &lt;- 33\r\na &lt;- 44\r\nA\r\n<\/code><\/pre>\n<pre>## [1] 33\r\n<\/pre>\n<pre><code class=\"r\">a\r\n<\/code><\/pre>\n<pre>## [1] 44\r\n<\/pre>\n<ol>\n<li>The tag # indicates a comment<\/li>\n<\/ol>\n<h2 id=\"toc_3\">R functions<\/h2>\n<p>An R function is used by typing its name followed by its arguments (also called parameters) between parentheses.<\/p>\n<p><strong>Example:<\/strong><br \/>\n<code>seq( )<\/code> is a function for generating a sequence of numbers. Its arguments are <code>arg1=from<\/code>, which specifies the first number of the sequence, <code>arg2= to<\/code>, last number of the sequence, and <code>arg3=by<\/code>, the increment of the sequence.<\/p>\n<pre><code class=\"r\">seq(10,80, 2) # generates a sequence from 10 to 80 with increment 2\r\n<\/code><\/pre>\n<pre>##  [1] 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54\r\n## [24] 56 58 60 62 64 66 68 70 72 74 76 78 80\r\n<\/pre>\n<pre>The number between brackets at the beginning of each line of the output indicates the position of the first element of each row: 10 is the first element of the output and 56 is the 24th element of the output\r\n<\/pre>\n<h2 id=\"toc_4\">Help and documentation<\/h2>\n<p><code>help( )<\/code> or <code>?<\/code> : provides information about a function or an object<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre>help(mean)\r\n?mean\r\n<\/pre>\n<p><code>help.search( )<\/code>: provides information about a topic<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre>help.search(\"logistic regression\")\r\n<\/pre>\n<h2 id=\"toc_5\">List and remove objects<\/h2>\n<p><code>ls()<\/code> Lists objects in current environment<\/p>\n<p><code>rm(x)<\/code> Removes object x in current environment<\/p>\n<p><code>rm(list = ls())<\/code> Removes all objects from current environment<\/p>\n<h2 id=\"toc_6\">Working directory<\/h2>\n<p>It is important to specify your working directory, where your files and scripts are<br \/>\nstored, using the function <code>setwd( )<\/code>.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre><code class=\"r\">setwd(\"c:\/mydir\") # note: use \/ instead of \\\r\n<\/code><\/pre>\n<p>You can check which is your current working directory:<\/p>\n<pre><code class=\"r\">getwd()\r\n<\/code><\/pre>\n<h2 id=\"toc_7\">Data structures<\/h2>\n<h3 id=\"toc_8\">Vector<\/h3>\n<p>A vector is a sequence of data elements of the same type, numerical, character strings or logical. You can create a vector with the function <code>c( )<\/code><\/p>\n<p><code>c( )<\/code>: R function for creating a vector<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre><code class=\"r\">x&lt;-c(1, 3, -1, 2)\r\ny&lt;-c(\"a\", \"b\", \"c\")\r\n<\/code><\/pre>\n<pre><code class=\"r\">x\r\n<\/code><\/pre>\n<pre>## [1]  1  3 -1  2\r\n<\/pre>\n<pre><code class=\"r\">y\r\n<\/code><\/pre>\n<pre>## [1] \"a\" \"b\" \"c\"\r\n<\/pre>\n<p><code>length( )<\/code>: provides the number of elements of a vector<\/p>\n<p><code>seq(from=, to=, by=)<\/code>: creates a vector containing a sequence of numbers<\/p>\n<p><code>rep(x, times=)<\/code>: creates a vector by repeating a sequence a number of times<\/p>\n<p><strong>Examples<\/strong><\/p>\n<pre><code class=\"r\">seq(10,50,2)\r\n<\/code><\/pre>\n<pre>##  [1] 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50\r\n<\/pre>\n<pre><code class=\"r\">rep(c(1,0,3),4)\r\n<\/code><\/pre>\n<pre>##  [1] 1 0 3 1 0 3 1 0 3 1 0 3\r\n<\/pre>\n<p>\u261e Perform Exercices 1 to 4, pg 4 document <a href=\"https:\/\/gsp.humboldt.edu\/olm\/R\/Tutorials\/BestFirstRTutorial.pdf\">\u201cR: A self-learn tutorial\u201d<\/a><\/p>\n<h4 id=\"toc_9\">Accessing the elements of a vector<\/h4>\n<p>Elements in a vector are addressed by bracket indexing <code>[ ]<\/code>:<\/p>\n<p><strong>Examples:<\/strong><br \/>\nConsider a vector x with 10 components<\/p>\n<pre><code class=\"r\">x&lt;-c(-1, 2, 7, 3, -4, 5, 1, 0, -2, 1)\r\n<\/code><\/pre>\n<pre><code class=\"r\">x[3] #returns the third element of vector x\r\n<\/code><\/pre>\n<pre>## [1] 7\r\n<\/pre>\n<p>You can get consecutive elements of a vector by using <code>:<\/code><\/p>\n<pre><code class=\"r\">x[2:5] #returns the elements in positions 2, 3, 4 and 5 of vector x\r\n<\/code><\/pre>\n<pre>## [1]  2  7  3 -4\r\n<\/pre>\n<p>You can get non consecutive elements of a vector by using function <code>c()<\/code>:<\/p>\n<pre><code class=\"r\">x[c(1,3,7)] #returns the elements in positions 1, 3 and 7 of vector x\r\n<\/code><\/pre>\n<pre>## [1] -1  7  1\r\n<\/pre>\n<p>You can exclude elements of a vector with the sign <code>-<\/code> before the indices you want to exclude<\/p>\n<pre><code class=\"r\">x[-c(2,5,8)] #returns all the elements in x except those in positions 2, 5 and 8\r\n<\/code><\/pre>\n<pre>## [1] -1  7  3  5  1 -2  1\r\n<\/pre>\n<p>\u261e Read section 3 from document <a href=\"http:\/\/www.nceas.ucsb.edu\/files\/scicomp\/Dloads\/RProgramming\/BestFirstRTutorial.pdf\">\u201cR: A self-learn tutorial\u201d<\/a> and Perform<br \/>\nExercices 1 and 2, pg 5<\/p>\n<h4 id=\"toc_10\">Assignment of new values<\/h4>\n<p>You can modify the value of an element in a vector with <code>&lt;-<\/code>:<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre><code class=\"r\">x[3]&lt;-5  # changes the third element in x by a 5\r\n<\/code><\/pre>\n<pre><code class=\"r\">x  # the third element in x was a 7 and now is a 5\r\n<\/code><\/pre>\n<pre>##  [1] -1  2  5  3 -4  5  1  0 -2  1\r\n<\/pre>\n<p><strong>Example:<\/strong><br \/>\nIn this example we want to change the negative elements in x by a 99. For this, we specify the condition <code>x&lt;0<\/code> between brackets<\/p>\n<pre><code class=\"r\">x[x&lt;0]&lt;-99  # assigns a 99 to the elements in x that are &lt;0\r\n<\/code><\/pre>\n<pre><code class=\"r\">x  # the initial negative elements in x have been substituted by a 99\r\n<\/code><\/pre>\n<pre>##  [1] 99  2  5  3 99  5  1  0 99  1\r\n<\/pre>\n<p>When programming new functions you may need to create an empty vector.<\/p>\n<pre>x&lt;-numeric() # This creates a numeric vector\r\n<\/pre>\n<pre>x&lt;-NULL # This creates a vector without specifying the data type\r\n<\/pre>\n<p>You can create logical vectors<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre><code class=\"r\">x&lt;-c(1, 3, -1, 2)\r\nx&gt;0   # answers TRUE or FALSE to the condition x&gt;0 for each element in x\r\n<\/code><\/pre>\n<pre>## [1]  TRUE  TRUE FALSE  TRUE\r\n<\/pre>\n<p>\u261e Read <a href=\"http:\/\/www.r-tutor.com\/r-introduction\/vector\">http:\/\/www.r-tutor.com\/r-introduction\/vector<\/a><\/p>\n<h3 id=\"toc_11\">Matrix<\/h3>\n<p>A matrix is a collection of data elements of the same type arranged in a two-dimensional rectangular layout.<\/p>\n<p><code>matrix( )<\/code>: R function for creating a matrix<\/p>\n<p><strong>Example:<\/strong><br \/>\nBy default, matrices are filled by columns<\/p>\n<pre><code class=\"r\">x&lt;-matrix(c(1,2,3,4,5,6,7,8), ncol=4)\r\nx\r\n<\/code><\/pre>\n<pre>##      [,1] [,2] [,3] [,4]\r\n## [1,]    1    3    5    7\r\n## [2,]    2    4    6    8\r\n<\/pre>\n<p><strong>Example:<\/strong><br \/>\nMatrices can also be filled by rows by specifying <code>byrow = TRUE<\/code>:<\/p>\n<pre><code class=\"r\">x&lt;-matrix(c(1,2,3,4,5,6,7,8), nrow=2, byrow = TRUE)\r\nx\r\n<\/code><\/pre>\n<pre>##      [,1] [,2] [,3] [,4]\r\n## [1,]    1    2    3    4\r\n## [2,]    5    6    7    8\r\n<\/pre>\n<h4 id=\"toc_12\">Dimension of a matrix<\/h4>\n<p><code>dim( )<\/code>: provides the number of rows and number of columns of a matrix<\/p>\n<pre><code class=\"r\">dim(x)\r\n<\/code><\/pre>\n<pre>## [1] 2 4\r\n<\/pre>\n<h4 id=\"toc_13\">Accessing elements of a matrix<\/h4>\n<p>Elements of a matrix are addressed with brackets by specifying the row and the column of the element: <code>[row,column]<\/code><\/p>\n<p><strong>Examples:<\/strong><\/p>\n<pre><code class=\"r\">x[2,4] # the element in the second row and the forth column of matrix x\r\n<\/code><\/pre>\n<pre>## [1] 8\r\n<\/pre>\n<pre><code class=\"r\">x[2, ] # vector containing all the elements of the second row of matrix x\r\n<\/code><\/pre>\n<pre>## [1] 5 6 7 8\r\n<\/pre>\n<pre><code class=\"r\">x[ ,4] # vector containing all the elements of the forth column of matrix x\r\n<\/code><\/pre>\n<pre>## [1] 4 8\r\n<\/pre>\n<pre><code class=\"r\">x[2 ,1:3] # vector containing the elements in columns 1 to 3 of the second row of matrix x\r\n<\/code><\/pre>\n<pre>## [1] 5 6 7\r\n<\/pre>\n<pre><code class=\"r\">x[,c(2,4)] # matrix containing the second and forth columns of matrix x\r\n<\/code><\/pre>\n<pre>##      [,1] [,2]\r\n## [1,]    2    4\r\n## [2,]    6    8\r\n<\/pre>\n<pre><code class=\"r\">x[,-2] # matrix containing all columns in x except the second one\r\n<\/code><\/pre>\n<pre>##      [,1] [,2] [,3]\r\n## [1,]    1    3    4\r\n## [2,]    5    7    8\r\n<\/pre>\n<p>\u261e Read section 4 from document<a href=\"http:\/\/www.nceas.ucsb.edu\/files\/scicomp\/Dloads\/RProgramming\/BestFirstRTutorial.pdf\">\u201cR: A self-learn tutorial\u201d<\/a>\u201c and Perform<br \/>\nExercices 1 and 2, pg 8<\/p>\n<h4 id=\"toc_14\">Adding new columns or rows to a matrix<\/h4>\n<p>Using <code>cbind( )<\/code> or <code>rbind( )<\/code> you can also create a matrix by putting together<br \/>\nseveral vectors in columns or in rows, respectively<\/p>\n<p><strong>Example:<\/strong> Let&#8217;s x, y, and z denote three vectors of length 5:<\/p>\n<pre><code class=\"r\">x&lt;-c(1, 2, 3, 4, 5)\r\ny&lt;-c(0, 1, -1, 2, 1)\r\nz&lt;-c(-2, -3, 0, 1, 2)\r\n<\/code><\/pre>\n<pre><code class=\"r\">cbind(x,y,z) # binds the 3 vectors as columns, the result is a matrix with 5 rows and 3 columns\r\n<\/code><\/pre>\n<pre>##      x  y  z\r\n## [1,] 1  0 -2\r\n## [2,] 2  1 -3\r\n## [3,] 3 -1  0\r\n## [4,] 4  2  1\r\n## [5,] 5  1  2\r\n<\/pre>\n<pre><code class=\"r\">rbind(x,y,z) # binds the 3 vectors as rows, the result is a matrix with 3 rows and 5 columns\r\n<\/code><\/pre>\n<pre>##   [,1] [,2] [,3] [,4] [,5]\r\n## x    1    2    3    4    5\r\n## y    0    1   -1    2    1\r\n## z   -2   -3    0    1    2\r\n<\/pre>\n<h4 id=\"toc_15\">Operations with matrices<\/h4>\n<pre><code class=\"r\">A&lt;-matrix(1:12, ncol=4) # By default, the elements of the matrix are filled by columns\r\nA\r\n<\/code><\/pre>\n<pre>##      [,1] [,2] [,3] [,4]\r\n## [1,]    1    4    7   10\r\n## [2,]    2    5    8   11\r\n## [3,]    3    6    9   12\r\n<\/pre>\n<pre><code class=\"r\">B&lt;-matrix(rep(1:3,4),ncol=4)\r\nB\r\n<\/code><\/pre>\n<pre>##      [,1] [,2] [,3] [,4]\r\n## [1,]    1    1    1    1\r\n## [2,]    2    2    2    2\r\n## [3,]    3    3    3    3\r\n<\/pre>\n<pre><code class=\"r\">C&lt;-matrix(1:16, ncol=4, byrow=T)  # When byrow=T, the elements of the matrix are filled by rows\r\nC\r\n<\/code><\/pre>\n<pre>##      [,1] [,2] [,3] [,4]\r\n## [1,]    1    2    3    4\r\n## [2,]    5    6    7    8\r\n## [3,]    9   10   11   12\r\n## [4,]   13   14   15   16\r\n<\/pre>\n<pre><code class=\"r\">A+B # sum element by element\r\n<\/code><\/pre>\n<pre>##      [,1] [,2] [,3] [,4]\r\n## [1,]    2    5    8   11\r\n## [2,]    4    7   10   13\r\n## [3,]    6    9   12   15\r\n<\/pre>\n<pre>A+C # error: the sum requires that dim(A)=dim(C)\r\n<\/pre>\n<pre><code class=\"r\">A*B # product element by element\r\n<\/code><\/pre>\n<pre>##      [,1] [,2] [,3] [,4]\r\n## [1,]    1    4    7   10\r\n## [2,]    4   10   16   22\r\n## [3,]    9   18   27   36\r\n<\/pre>\n<pre>A*C # error: the product element by element requires that dim(A)=dim(C)\r\n<\/pre>\n<pre><code class=\"r\">A%*%C # matrix product: each element is the scalar product of a row of the first matrix and a column of the second matrix\r\n<\/code><\/pre>\n<pre>##      [,1] [,2] [,3] [,4]\r\n## [1,]  214  236  258  280\r\n## [2,]  242  268  294  320\r\n## [3,]  270  300  330  360\r\n<\/pre>\n<pre>A%*%B # error: matrix product requires that ncol(A)=nrow(B)\r\n<\/pre>\n<pre><code class=\"r\">t(A) # transposed matrix of A\r\n<\/code><\/pre>\n<pre>##      [,1] [,2] [,3]\r\n## [1,]    1    2    3\r\n## [2,]    4    5    6\r\n## [3,]    7    8    9\r\n## [4,]   10   11   12\r\n<\/pre>\n<pre><code class=\"r\">A^2 # each element of A is squared\r\n<\/code><\/pre>\n<pre>##      [,1] [,2] [,3] [,4]\r\n## [1,]    1   16   49  100\r\n## [2,]    4   25   64  121\r\n## [3,]    9   36   81  144\r\n<\/pre>\n<pre><code class=\"r\">C%*%C # matrix product of C by C\r\n<\/code><\/pre>\n<pre>##      [,1] [,2] [,3] [,4]\r\n## [1,]   90  100  110  120\r\n## [2,]  202  228  254  280\r\n## [3,]  314  356  398  440\r\n## [4,]  426  484  542  600\r\n<\/pre>\n<p>\u261e Read <a href=\"http:\/\/www.r-tutor.com\/r-introduction\/matrix\">http:\/\/www.r-tutor.com\/r-introduction\/matrix<\/a><\/p>\n<h3 id=\"toc_16\">Data frame<\/h3>\n<p>A data frame is a very important data type in R since data files for statistical analysis are read and stored in data frames (see below Reading and writing data files).<\/p>\n<p>A data frame is a table where the top line of the table, called the header, contains<br \/>\nthe column names. Each column of a data frame is a vector, thus, the elements of<br \/>\neach column should be of the same type but the elements of different columns can<br \/>\nbe of different type.<\/p>\n<p><code>data.frame( )<\/code>: R function for creating a data frame<\/p>\n<p>When a data frame is printed, the name of the row (or the number of the row) is<br \/>\nshown at the beginning of the row.<\/p>\n<p><strong>Example:<\/strong> The following script creates a dataframe called &#8220;students\u201d with 2<br \/>\ncolumns: name and age:<\/p>\n<pre><code class=\"r\">name&lt;-c(\"John\",\"Paul\",\"Mary\")\r\nage&lt;-c(21,23,32)\r\nstudents&lt;-data.frame(name, age)\r\n<\/code><\/pre>\n<pre><code class=\"r\">students\r\n<\/code><\/pre>\n<pre>##   name age\r\n## 1 John  21\r\n## 2 Paul  23\r\n## 3 Mary  32\r\n<\/pre>\n<p>The same dataframe could also be created with the following code:<\/p>\n<pre><code class=\"r\">students&lt;-data.frame(name=c(\"John\",\"Paul\",\"Mary\"),age=c(21,23,32))\r\n<\/code><\/pre>\n<h4 id=\"toc_17\">Functions for data frames<\/h4>\n<p><code>nrow( )<\/code>: number of rows of a data frame<\/p>\n<p><code>ncol( )<\/code>: number of columns of a data frame<\/p>\n<p><code>rownames( )<\/code>: vector containing the row names of a data frame<\/p>\n<p><code>colnames( )<\/code>: vector containing the column names of a data frame<\/p>\n<p><code>head( )<\/code>: shows the first rows of a data frame<\/p>\n<p><code>tail( )<\/code>: shows the last rows of a data frame<\/p>\n<h4 id=\"toc_18\">Accessing the elements of a data frame<\/h4>\n<p>Elements of a data frame are addressed with <code>[row,column]<\/code><\/p>\n<p><strong>Examples:<\/strong><\/p>\n<pre><code class=\"r\">students[1,2]   # element in row 1 and column 2 in data frame \"student\"\r\n<\/code><\/pre>\n<pre>## [1] 21\r\n<\/pre>\n<pre><code class=\"r\">students[1,\"age\"]   # element in row 1 and column \"age\" in data frame \"student\"\r\n<\/code><\/pre>\n<pre>## [1] 21\r\n<\/pre>\n<h4 id=\"toc_19\">Retrieving the columns of a data frame<\/h4>\n<p>The columns (variables) of a data frame can be referred in different ways:<\/p>\n<p>1) name1$name2 where name1 is the name of the data frame and name2 is the name of the column<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre><code class=\"r\">students$age # we should specify both, the name of the data frame, \"students\" and the name of the variable, \"age\"\r\n<\/code><\/pre>\n<pre>## [1] 21 23 32\r\n<\/pre>\n<p>2) name1[,\u201cname2\u201d] where name1 is the name of the data frame and name2 is the name of the column<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre><code class=\"r\">students[,\"age\"]\r\n<\/code><\/pre>\n<pre>## [1] 21 23 32\r\n<\/pre>\n<p>3) name1[,num] where name1 is the name of the data frame and num is the column number<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre><code class=\"r\">students[,2]\r\n<\/code><\/pre>\n<pre>## [1] 21 23 32\r\n<\/pre>\n<p>4) name1[[num]] where name1 is the name of the data frame and num is the column number<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre><code class=\"r\">students[[2]]\r\n<\/code><\/pre>\n<pre>## [1] 21 23 32\r\n<\/pre>\n<p>The columns of a data frame can also be referred directly with its name without specifying the data frame name provided that, previously, the data frame has been attached<\/p>\n<p>\u261e Read <a href=\"http:\/\/www.r-tutor.com\/r-introduction\/data-frame\">http:\/\/www.r-tutor.com\/r-introduction\/data-frame<\/a><\/p>\n<p>\u261e More info on R data frames:\u00a0\u00a0<a href=\"https:\/\/www.gastonsanchez.com\/intro2cwd\/dataframes.html\" target=\"_blank\" rel=\"noopener\">https:\/\/www.gastonsanchez.com\/intro2cwd\/dataframes.html<\/a><\/p>\n<h4 id=\"toc_20\">Subsetting<\/h4>\n<p>You can create a new data frame consisting of a subset of the data in a different<br \/>\ndata frame by indexing the required restrictions.<\/p>\n<p><strong>Example:<\/strong> Creating a new data frame named \u201cstudents2\u201d which is a subset of<br \/>\n\u201cstudents\u201d but only includes those students younger than 30 years old.<\/p>\n<pre><code class=\"r\">students2&lt;-students[students$age&lt;30, ] # the subset is created by specifying the restriction: only those rows (individuals) with age&lt;30 are selected\r\nstudents2\r\n<\/code><\/pre>\n<pre>##   name age\r\n## 1 John  21\r\n## 2 Paul  23\r\n<\/pre>\n<h3 id=\"toc_21\">List<\/h3>\n<p>A list is a vector containing objects of different type.<\/p>\n<p><code>list( )<\/code>: R function for creating a list<\/p>\n<p><strong>Example<\/strong><\/p>\n<p>Lets create a list containing three objects, a character vector x, a matrix M and a numerical vector y.<\/p>\n<pre><code class=\"r\">x&lt;-c(\"a\", \"b\", \"c\")\r\nM&lt;-matrix(1:4, 2)\r\ny&lt;-c(1.3, 2.5, 5.7, 1.8, 3.1)\r\nmylist&lt;-list(letters=x, mymatrix=M, numbers=y)  # we assign new names to x, M and y\r\n<\/code><\/pre>\n<p>The objects in a list are called attributes. Function <code>attributes()<\/code> provides the names of the elements contained in a list.<\/p>\n<p><strong>Example<\/strong><\/p>\n<p>\u201cmylist\u201d contains three objects or attributes:<\/p>\n<pre><code class=\"r\">attributes(mylist)\r\n<\/code><\/pre>\n<pre>## $names\r\n## [1] \"letters\"  \"mymatrix\" \"numbers\"\r\n<\/pre>\n<h4 id=\"toc_22\">Accessing the elements in a list with simple brackets<\/h4>\n<p>If you use simple brackes <code>[]<\/code> you obtain a list slice<\/p>\n<p><strong>Example<\/strong><\/p>\n<pre><code class=\"r\">mylist[2]   # This provides a new list containing one object, matrix M, the second attribute of \"mylist\"\r\n<\/code><\/pre>\n<pre>## $mymatrix\r\n##      [,1] [,2]\r\n## [1,]    1    3\r\n## [2,]    2    4\r\n<\/pre>\n<pre><code class=\"r\">mylist[3]   # This provides a new list containing vector \"numbers\", the third attribute of \"mylist\"\r\n<\/code><\/pre>\n<pre>## $numbers\r\n## [1] 1.3 2.5 5.7 1.8 3.1\r\n<\/pre>\n<pre><code class=\"r\">mylist[2:3]   # This provides a new list containing two objects, the second and third attributes of \"mylist\"\r\n<\/code><\/pre>\n<pre>## $mymatrix\r\n##      [,1] [,2]\r\n## [1,]    1    3\r\n## [2,]    2    4\r\n##\r\n## $numbers\r\n## [1] 1.3 2.5 5.7 1.8 3.1\r\n<\/pre>\n<h4 id=\"toc_23\">Accessing the elements in a list with double brackets<\/h4>\n<p>If you use double brackes <code>[[]]<\/code> you obtain the object.<\/p>\n<p><strong>Example<\/strong><\/p>\n<pre><code class=\"r\">mylist[[2]] # This provides matrix M\r\n<\/code><\/pre>\n<pre>##      [,1] [,2]\r\n## [1,]    1    3\r\n## [2,]    2    4\r\n<\/pre>\n<p>Compare objects mylist[2] and mylist[[2]] using <code>class( )<\/code>, an R function that provides the type of an object<\/p>\n<pre><code class=\"r\">class(mylist[2]) # mylist[2] is a list containing a matrix\r\n<\/code><\/pre>\n<pre>## [1] \"list\"\r\n<\/pre>\n<pre><code class=\"r\">class(mylist[[2]]) # mylist[[2]] is a matrix\r\n<\/code><\/pre>\n<pre>## [1] \"matrix\"\r\n<\/pre>\n<p>If we want to retrieve the vector \u201cnumbers\u201d we should use double brackets<\/p>\n<pre><code class=\"r\">mylist[[3]]  # This provides vector \"numbers\"\r\n<\/code><\/pre>\n<pre>## [1] 1.3 2.5 5.7 1.8 3.1\r\n<\/pre>\n<p>Compare the use of simple and double brackets to obtain the mean of vector \u201cnumbers\u201d<\/p>\n<pre><code class=\"r\">mean(mylist[3])  # This provides an warning and a NA (not available) result because function mean() expects a vector, not a list, for its argument\r\n<\/code><\/pre>\n<pre>## Warning in mean.default(mylist[3]): argument is not numeric or logical:\r\n## returning NA\r\n<\/pre>\n<pre>## [1] NA\r\n<\/pre>\n<pre><code class=\"r\">mean(mylist[[3]])  # This is correct because the argument mylist[[3]] of mean() is a vector\r\n<\/code><\/pre>\n<pre>## [1] 2.88\r\n<\/pre>\n<h4 id=\"toc_24\">Accessing the elements in a list with the dollar symbol<\/h4>\n<p>An alternative to the double brackes for accessing an object in a list or data frame is through the syntax name1$name2 where name1 is the name of the list and name2 is the name of the object or attribute.<\/p>\n<p><strong>Example<\/strong><\/p>\n<pre><code class=\"r\">mylist$mymatrix # This provides matrix M\r\n<\/code><\/pre>\n<pre>##      [,1] [,2]\r\n## [1,]    1    3\r\n## [2,]    2    4\r\n<\/pre>\n<h4 id=\"toc_25\">Retrieving objects from the output of a statistical procedure<\/h4>\n<p>The output of most statistical procedures is stored as a list. The objects in the output can be retrieved using double brackets <code>[[]]<\/code><\/p>\n<p><strong>Example<\/strong><\/p>\n<p>We want to retrieve the residuals of a linear regression model:<\/p>\n<pre><code class=\"r\">x&lt;-c(1, 2, 3, 4, 5)\r\ny&lt;-c(1.3, 2.4, 1.6, 2.3, 2.1)\r\nm1&lt;-lm(y~x)\r\nattributes(m1)  # this provides the names of the attributes of model m1\r\n<\/code><\/pre>\n<pre>## $names\r\n##  [1] \"coefficients\"  \"residuals\"     \"effects\"       \"rank\"\r\n##  [5] \"fitted.values\" \"assign\"        \"qr\"            \"df.residual\"\r\n##  [9] \"xlevels\"       \"call\"          \"terms\"         \"model\"\r\n##\r\n## $class\r\n## [1] \"lm\"\r\n<\/pre>\n<p>The residuals of the regression model are the second attribute of m1 and can be retrieved as follows<\/p>\n<pre><code class=\"r\">m1[[2]]\r\n<\/code><\/pre>\n<pre>##     1     2     3     4     5\r\n## -0.34  0.61 -0.34  0.21 -0.14\r\n<\/pre>\n<p>An alternative syntax for obtaining the residuals is<\/p>\n<pre><code class=\"r\">m1$residuals\r\n<\/code><\/pre>\n<pre>##     1     2     3     4     5\r\n## -0.34  0.61 -0.34  0.21 -0.14\r\n<\/pre>\n<p>\u261e Read <a href=\"http:\/\/www.r-tutor.com\/r-introduction\/list\">http:\/\/www.r-tutor.com\/r-introduction\/list<\/a><\/p>\n<p>The output of some statistical procedures are stored as <a href=\"http:\/\/adv-r.had.co.nz\/S4.html\">S4 objects<\/a>. To access slots of an S4 object you should use <code>@<\/code> instead of <code>$<\/code>.<\/p>\n<h2 id=\"toc_26\">Data types and factor variables<\/h2>\n<h3 id=\"toc_27\">Data types<\/h3>\n<p>There are several R data types, the most important are numeric, integer, logical and character.<\/p>\n<p>\u261e Read <a href=\"http:\/\/www.r-tutor.com\/r-introduction\/basic-data-types\">http:\/\/www.r-tutor.com\/r-introduction\/basic-data-types<\/a><\/p>\n<p>By default, any number is considered a numeric data even when the number only<br \/>\nindicates a category of a categorical variable.<\/p>\n<h3 id=\"toc_28\">Factor variables <code>factor( )<\/code><\/h3>\n<p>It is recommended to convert any categorical variable into a factor<br \/>\nusing function <code>factor( )<\/code>. This function assigns an integer 1, 2, \u2026, k (called levels)<br \/>\nto each category of the original variable where k is the number of different<br \/>\ncategories.<\/p>\n<p>*<em>Example: *<\/em><\/p>\n<p>The following script creates a dataframe called \u201cexample\u201d with 3<br \/>\nvariables: Y (diseased indicator), treatment (0=placebo, 1=drug) and bmi<br \/>\n(body mass index)<\/p>\n<pre><code class=\"r\">Y&lt;-c(\"diseased\", \"not-diseased\", \"not-diseased\", \"diseased\",\"not-diseased\")\r\ntreatment&lt;-c(0, 0, 0, 1, 1)\r\nbmi&lt;-c(21.52, 22.73, 21.89, 20.17, 24.13)\r\nexample &lt;-data.frame(Y, treatment, bmi)\r\n<\/code><\/pre>\n<p>We can check the data types of the three variables with function <code>class( )<\/code>:<\/p>\n<pre><code class=\"r\">class(Y)\r\n<\/code><\/pre>\n<pre>## [1] \"character\"\r\n<\/pre>\n<pre><code class=\"r\">class(treatment)\r\n<\/code><\/pre>\n<pre>## [1] \"numeric\"\r\n<\/pre>\n<pre><code class=\"r\">class(bmi)\r\n<\/code><\/pre>\n<pre>## [1] \"numeric\"\r\n<\/pre>\n<p>Variable treatment is numeric and would be analyzed as a continuous variable. We should transform this variable to a factor by specifying their <code>levels<\/code> (categories) and <code>labels<\/code> (explanation of each category):<\/p>\n<pre><code class=\"r\">example$treatment&lt;-factor(example$treatment, levels=c(0,1), labels=c(\"placebo\", \"drug\"))\r\n<\/code><\/pre>\n<pre><code class=\"r\">example$treatment\r\n<\/code><\/pre>\n<pre>## [1] placebo placebo placebo drug    drug\r\n## Levels: placebo drug\r\n<\/pre>\n<p>Character data, such as Y, can also be transformed to a factor variable. If <code>levels<\/code> are not specified, by default, the levels of the categories are assigned according to the alphabetic or numeric order. For variable Y, level 1 will be \u201cdiseased\u201d and level 2 will be \u201cnot-diseased\u201d:<\/p>\n<pre><code class=\"r\">example$Y&lt;-factor(Y)\r\n<\/code><\/pre>\n<pre><code class=\"r\">example$Y\r\n<\/code><\/pre>\n<pre>## [1] diseased     not-diseased not-diseased diseased     not-diseased\r\n## Levels: diseased not-diseased\r\n<\/pre>\n<p>In most statistical procedures, the category with level=1 is taken as the reference<br \/>\ncategory. If we want to change the reference category we will specify the levels<br \/>\nof the variables with the first level corresponding to the reference category.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre><code class=\"r\">example$Y&lt;-factor(Y, levels=c(\"not-diseased\", \"diseased\"))\r\n<\/code><\/pre>\n<pre><code class=\"r\">example$Y\r\n<\/code><\/pre>\n<pre>## [1] diseased     not-diseased not-diseased diseased     not-diseased\r\n## Levels: not-diseased diseased\r\n<\/pre>\n<p>Now, the reference category for Y is \u201cnot-diseased\u201d<\/p>\n<p><a href=\"http:\/\/www.statmethods.net\/input\/valuelabels.html\">http:\/\/www.statmethods.net\/input\/valuelabels.html<\/a><\/p>\n<h2 id=\"toc_29\">Reading and writing data files<\/h2>\n<p>You can import your data from a file to R without coding, using <span style=\"color: #993300\"><strong>RStudio<\/strong><\/span>: File -&gt; Import Dataset -&gt; From &#8230; (text, Excel, SPSS, SAS or stata).<\/p>\n<p>Alternatively, you can use R coding:<\/p>\n<p>&nbsp;<\/p>\n<h3 id=\"toc_30\">txt files<\/h3>\n<p><code>read.table( )<\/code>: this function reads a text data file and stores the values into a data frame<\/p>\n<p><code>header=T<\/code> : first row of the data file contains the names of the columns or variables<br \/>\n<code>sep=\"\"<\/code> : the values of each row are separated by a space<br \/>\n<code>sep=\"\\t\"<\/code> : the values of each row are separated by a tabulation<br \/>\n<code>sep=\",\"<\/code> : the values of each row are separated by a comma<br \/>\n<code>dec=\".\"<\/code>: the decimal symbol is a point<\/p>\n<p><strong>Example<\/strong><\/p>\n<pre><code class=\"r\">example &lt;- read.table(\"treatment.txt\", header=F, sep=\"\")\r\n# This instruction reads file \"treatment.txt\" and creates the dataframe \"example\"\r\n<\/code><\/pre>\n<p><code>write.table( )<\/code>: this function writes a data frame into a text file<\/p>\n<p><strong>Example<\/strong><\/p>\n<pre><code class=\"r\">write.table(treatment, file=\"treatment.txt\", row.names=FALSE)\r\n# This instruction writes the dataframe \"treatment\" in file \"treatment.txt\"\r\n# row.names=FALSE prevents R for printint the names of the rows (or just the row numbers) in the output file\r\n<\/code><\/pre>\n<p>\u261e Read Section 8 \u201cReading and writing data files\u201d from document <a href=\"http:\/\/cran.r-project.org\/doc\/contrib\/Torfs+Brauer-Short-R-Intro.pdf\">\u201cA (very) short introduction to R\u201d<\/a><br \/>\nby P. Torfs and C. Brauer and do the proposed<br \/>\nexercise at the end of the section.<\/p>\n<h3 id=\"toc_31\">csv files<\/h3>\n<p>One convenient format for storing data files is csv, \u201ccomma separated values\u201d, since they can be open easily in Excel<\/p>\n<p><code>read.csv( )<\/code><\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre><code class=\"r\">Example &lt;- read.csv(\"example.csv\", header=T, sep=\",\", dec=\".\");\r\n<\/code><\/pre>\n<p><code>write.csv( )<\/code>: this function writes a data frame into a csv file<\/p>\n<p><strong>Example<\/strong><\/p>\n<pre><code class=\"r\">write.csv(treatment, file=\"treatment.csv\", row.names=FALSE)\r\n# This instruction writes the dataframe \"treatment\" in file \"treatment.csv\"\r\n# row.names=FALSE prevents R from printing the names of the rows (or just the row numbers) in the output file\r\n<\/code><\/pre>\n<h3 id=\"toc_32\">Excel files<\/h3>\n<p>You can read Excel files with function <code>read.xlsx( )<\/code> from the package <code>openxlsx<\/code>. In the next section you will learn how to install this package.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre><code class=\"r\">data &lt;- read.xlsx(xlsxFile = \"my_data.xlsx\", sheet = \"sheet2\", skipEmptyRows = T)<\/code><\/pre>\n<p>&nbsp;<\/p>\n<h2 id=\"toc_33\">Libraries and packages<\/h2>\n<p>All R functions and datasets are stored in packages.<\/p>\n<h3 id=\"toc_34\">Libraries\/Packages<\/h3>\n<p>R comes with a standard set of packages. Others are available for download and<br \/>\ninstallation.<\/p>\n<p><strong>Standard packages:<\/strong> The standard (or base) packages are considered part of the R<br \/>\nsource code. They contain the basic functions that allow R to work, and the<br \/>\ndatasets and standard statistical and graphical functions. They should be<br \/>\nautomatically available in any R installation.<\/p>\n<p><strong>Contributed packages:<\/strong> There are thousands of contributed packages for R,<br \/>\nwritten by many different authors. Some of these packages implement specialized<br \/>\nstatistical methods. Some (the recommended packages) are distributed with every<br \/>\nbinary distribution of R.<\/p>\n<p>Most packages are available for download from <strong>CRAN<\/strong> and other repositories such as<br \/>\n<strong>Bioconductor<\/strong>, a large repository of tools for the analysis and comprehension of<br \/>\nhigh-throughput genomic data.<\/p>\n<p>Once installed, a package has to be loaded into the session to be used.<\/p>\n<h3 id=\"toc_35\">Install packages from CRAN<\/h3>\n<p>Using an R package or library for the first time requires two steps: installing the library and loading the library with the following functions:<\/p>\n<p><code>install.packages()<\/code>: Install the package<\/p>\n<p><code>library()<\/code>: load the package<\/p>\n<p><strong>Example:<\/strong> How to install and load the library \u201csurvival\u201d?<\/p>\n<pre>install.packages(\"survival\") # you only need to do this once\r\nlibrary(survival) # load library\r\n<\/pre>\n<h3 id=\"toc_36\">Install packages from Bioconductor<\/h3>\n<p>Bioconductor <a href=\"http:\/\/www.bioconductor.org\/\">http:\/\/www.bioconductor.org\/<\/a> provides tools for the analysis and<br \/>\ncomprehension of high-throughput genomic data.<\/p>\n<p><strong>New Bioconductor (R version 3.6.0 or newer). Install a Bioconductor package:<\/strong><\/p>\n<p>The new Bioconductor uses BiocManager to install packages.<\/p>\n<p><code>if (!requireNamespace(\"BiocManager\", quietly = TRUE))<br \/>\ninstall.packages(\"BiocManager\")<\/code><\/p>\n<p><code><span id=\"yui_3_17_2_1_1571329818218_42\"><span id=\"yui_3_17_2_1_1571329818218_41\"><span id=\"yui_3_17_2_1_1571329818218_40\"><span id=\"yui_3_17_2_1_1571329818218_39\"><span id=\"yui_3_17_2_1_1571329818218_38\"><span id=\"yui_3_17_2_1_1571329818218_37\"><span id=\"yui_3_17_2_1_1571329818218_36\">BiocManager::install(<\/span><\/span><\/span><\/span><\/span><\/span><\/span>)<\/code> \u00a0 install bioconductor packages<\/p>\n<p><code>library()<\/code>: load library<\/p>\n<p><strong>Old Bioconductor (R version older than 3.6.0). Install a Bioconductor package:<\/strong><\/p>\n<p>Old Bioconductor uses biocLite:<\/p>\n<p><code>source(\"http:\/\/bioconductor.org\/biocLite.R\")<\/code>: executes biocLite.R.<\/p>\n<p><code>biocLite()<\/code>: install bioconductor packages<\/p>\n<p><code>library()<\/code>: load library<\/p>\n<p><strong>Example:<\/strong> Installing \u201cBiostrings\u201d from new Bioconductor:<\/p>\n<pre>if (!requireNamespace(\"BiocManager\", quietly=TRUE))\r\ninstall.packages(\"BiocManager\")\r\n<\/pre>\n<pre>BiocManager::install(\"Biostrings\") # install Biostrings\r\n<\/pre>\n<pre>library(Biostrings) # load library Biostrings<\/pre>\n<p><strong>Example:<\/strong> Installing \u201cBiostrings\u201d from old Bioconductor:<\/p>\n<pre>source(\"http:\/\/bioconductor.org\/biocLite.R\") # executes biocLite.R.\r\n<\/pre>\n<pre>biocLite(\"Biostrings\") # install Biostrings\r\n<\/pre>\n<pre>library(Biostrings) # load library Biostrings\r\n<\/pre>\n<h2 id=\"toc_37\">Basic statistical functions<\/h2>\n<p>We will describe the principal statistical functions using the following example:<\/p>\n<pre><code class=\"r\">Y&lt;-c(\"diseased\", \"not-diseased\", \"not-diseased\", \"diseased\",\"not-diseased\")\r\ntreatment&lt;-c(0, 0, 0, 1, 1)\r\nbmi&lt;-c(21.52, 22.73, 21.89, 20.17, 24.13)\r\ntreatment&lt;-factor(treatment, levels=c(0,1), labels=c(\"placebo\", \"drug\"))\r\n<\/code><\/pre>\n<h3 id=\"toc_38\">Summary statistics<\/h3>\n<h4 id=\"toc_39\">Summary statistics of a numerical variable<\/h4>\n<pre><code class=\"r\">min(bmi) # minimum value of bmi\r\nmax(bmi) # maximum value of bmi\r\nmean(bmi) # mean or average bmi\r\nmedian(bmi) # median bmi\r\nsd(bmi) # standard deviation of bmi\r\nquantile(bmi, 0.25) # first quartile for bmi\r\nquantile(bmi, 0.75) # third quartile for bmi\r\nquantile(bmi, 0.95) # 95% quantile for bmi\r\nIQR(bmi) # interquartile rang of bmi\r\nsummary(bmi)  # provides the most important summary statistics for bmi\r\n<\/code><\/pre>\n<h4 id=\"toc_40\">Summary statistics of a character or factor variable<\/h4>\n<pre><code class=\"r\">table(treatment)  # frequency table\r\nprop.table(table(treatment))  # Table of relative frequencies\r\n100*prop.table(table(treatment))   # Table of percentages\r\n<\/code><\/pre>\n<h4 id=\"toc_41\">Correlation coefficient between two numerical variables<\/h4>\n<p><strong>Example<\/strong><\/p>\n<pre><code class=\"r\">x&lt;-c(2, 4, 1, 3, 6, 5)\r\ny&lt;-c(3, 5, 2, 2, 6, 3)\r\n<\/code><\/pre>\n<pre><code class=\"r\">cor(x,y)  # Pearson correlation coefficient\r\ncor(x,y, method=\"spearman\")  # Spearman correlation coefficient\r\n<\/code><\/pre>\n<h3 id=\"toc_42\">Test statistics<\/h3>\n<h4 id=\"toc_43\">t-test for the equality of two means from independent samples<\/h4>\n<p>The t-test is appropriate under the assumption of normal distributed data<\/p>\n<pre><code class=\"r\">t.test(bmi~treatment)   # by default variances are assumed different\r\nt.test(bmi~treatment, var.equal=T)   # variances are assumed equal\r\n<\/code><\/pre>\n<p>If we only want to retrieve the p-value of the test<\/p>\n<pre><code class=\"r\">t.test(bmi~treatment, var.equal=T)$p.value\r\n<\/code><\/pre>\n<h4 id=\"toc_44\">F test for the equality of two variances<\/h4>\n<pre><code class=\"r\">var.test(bmi~treatment)\r\n<\/code><\/pre>\n<h4 id=\"toc_45\">Wilcoxon test for the equality of two means from independent samples<\/h4>\n<p>The Wilcoxon test is the alternative to the t-test when the data is not normally distributed<\/p>\n<pre><code class=\"r\">wilcox.test(bmi~treatment)\r\n<\/code><\/pre>\n<h4 id=\"toc_46\">t.test for paired samples<\/h4>\n<pre><code class=\"r\">x1&lt;-c(2.7, 3.4, 1.8, 3.2, 6.4, 1.5)\r\nx2&lt;-c(3.1, 5.3, 2.1, 2.7, 6.8, 3.1)\r\n<\/code><\/pre>\n<pre><code class=\"r\">t.test(x1-x2, mu=0)\r\n<\/code><\/pre>\n<h4 id=\"toc_47\">Wilcoxon test for paired samples<\/h4>\n<pre><code class=\"r\">wilcox.test(x1,x2, paired=T)\r\n<\/code><\/pre>\n<h4 id=\"toc_48\">One-factor ANOVA for testing the equality of more than two means<\/h4>\n<p>The ANOVA is appropriate under the assumption of normal distributed data and homoscedasticity (equal variances)<\/p>\n<pre><code class=\"r\">y&lt;-c(2.7, 3.4, 1.8, 3.2, 6.4, 1.5, 3.1, 5.3, 2.1, 2.7, 6.8, 3.1)\r\nx&lt;-c(1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3)\r\n<\/code><\/pre>\n<pre><code class=\"r\">summary(aov(y~x))\r\n<\/code><\/pre>\n<h4 id=\"toc_49\">Kruskal-Wallis test for testing the equality of more than two means<\/h4>\n<p>The Kruskal-Wallis test is the alternative to the ANOVA when the data is not normally distributed<\/p>\n<pre><code class=\"r\">kruskal.test(y~x)\r\n<\/code><\/pre>\n<h3 id=\"toc_50\">Regression models<\/h3>\n<h4 id=\"toc_51\">linear regression<\/h4>\n<p>The outcome variable is continuous<\/p>\n<pre><code class=\"r\">y&lt;-c(2.7, 3.4, 1.8, 3.2, 6.4, 1.5, 3.1, 5.3, 2.1, 2.7, 6.8, 3.1)\r\nx1&lt;-c(1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3)\r\nx2&lt;-c(2, 3, 8, 2, 6, 1, 1, 3, 2, 2, 8, 1)\r\n<\/code><\/pre>\n<pre><code class=\"r\">summary(lm(y~x1+x2))\r\n<\/code><\/pre>\n<h4 id=\"toc_52\">logistic regression<\/h4>\n<p>The outcome variable is dychotomous<\/p>\n<pre><code class=\"r\">y&lt;-c(rep(1, 6), rep(0,6))\r\nx1&lt;-c(5.3, 2.1, 5.6, 2.1, 3.2, 1.2, 1.2, 3.1, 1.3, 2.4, 1.5, 2.6)\r\nx2&lt;-c(2, 3, 8, 2, 6, 1, 1, 3, 2, 2, 8, 1)\r\n<\/code><\/pre>\n<pre><code class=\"r\">summary(glm(y~x1+x2, family=binomial))\r\n<\/code><\/pre>\n<h2 id=\"toc_53\">Graphs with R<\/h2>\n<h3 id=\"toc_54\">Principal graphical representations<\/h3>\n<p>The general function for creating graphs in R is <code>plot( )<\/code><\/p>\n<p>Useful links with examples on creating graphs from Quick-R website <a href=\"http:\/\/www.statmethods.net:\">http:\/\/www.statmethods.net:<\/a><\/p>\n<p><a href=\"http:\/\/www.statmethods.net\/graphs\/density.html\"><strong>Histograms<\/strong><\/a> <code>hist()<\/code><\/p>\n<p><a href=\"http:\/\/www.statmethods.net\/graphs\/density.html\"><strong>Density plots<\/strong><\/a> <code>density()<\/code><\/p>\n<p><a href=\"http:\/\/www.statmethods.net\/graphs\/dot.html\"><strong>Dot plots<\/strong><\/a> <code>dotchart()<\/code><\/p>\n<p><a href=\"http:\/\/www.statmethods.net\/graphs\/bar.html\"><strong>Bar plots<\/strong><\/a> <code>barplot()<\/code><\/p>\n<p><a href=\"http:\/\/www.statmethods.net\/graphs\/line.html\"><strong>Line charts<\/strong><\/a> <code>lines()<\/code><\/p>\n<p><a href=\"http:\/\/www.statmethods.net\/graphs\/pie.html\"><strong>Pie charts<\/strong><\/a> <code>pie()<\/code><\/p>\n<p><a href=\"http:\/\/www.statmethods.net\/graphs\/boxplot.html\"><strong>Box plots<\/strong><\/a> <code>boxplot()<\/code><\/p>\n<p><a href=\"http:\/\/www.statmethods.net\/graphs\/scatterplot.html\"><strong>Scatter plots<\/strong><\/a> <code>scatterplot()<\/code><\/p>\n<p><a href=\"http:\/\/www.statmethods.net\/advgraphs\/parameters.html\"><strong>Graphical parameters<\/strong><\/a> <code>par()<\/code><\/p>\n<p><a href=\"http:\/\/gastonsanchez.com\/teaching\/r-graphical-parameters-cheatsheet.pdf\"><strong>R Graphical Parameters Cheat Sheet<\/strong> from Gaston Sanchez blog<\/a><\/p>\n<p><a href=\"http:\/\/www.statmethods.net\/advgraphs\/trellis.html\"><strong>Lattice graphs<\/strong><\/a><\/p>\n<p><a href=\"http:\/\/www.statmethods.net\/advgraphs\/ggplot2.html\"><strong>ggplot2 graphs<\/strong><\/a><\/p>\n<h3 id=\"toc_55\">Saving plots to a file<\/h3>\n<p><code>pdf()<\/code> redirects a plot to a pdf file and <code>dev.off()<\/code> stops R from redirecting new plots to files<\/p>\n<p><strong>Example<\/strong><\/p>\n<pre><code class=\"r\">pdf(\"normal_distribution.pdf\")\r\nhist(rnorm(100, mean=10, sd=3))\r\ndev.off()\r\n<\/code><\/pre>\n<h2 id=\"toc_56\">Programming with R<\/h2>\n<h3 id=\"toc_57\">Functions with R<\/h3>\n<p>You can program your own functions by specifying the function name, the<br \/>\narguments or parameters between brackets and the body of your function between curly brackets.<\/p>\n<p>The body of a function may contain several lines. <code>return()<\/code> is used to specify the output of the function. If <code>return()<\/code> is not specified, R returns the last executed line of the function.<\/p>\n<p><strong>Basic function structure:<\/strong><\/p>\n<pre>function.name &lt;- function(arguments) {\r\n  purpose of function i.e. computations involving the arguments\r\n}\r\n<\/pre>\n<p>The function is executed by <code>function.name(arguments)<\/code><\/p>\n<p><strong>Example<\/strong><\/p>\n<p>The following function computes the perimeter of a circumference. The function&#8217;s<br \/>\nname is \u201cPerimeter\u201d\u201c, the argument is the radius of the circumference<\/p>\n<pre><code class=\"r\">Perimeter &lt;- function(x) {\r\n  p &lt;- 2 * pi * x\r\n  return(p)\r\n}\r\n<\/code><\/pre>\n<p>You can use the perimeter functon to calculate the perimeter of a circumference of<br \/>\nany ratio x<\/p>\n<pre><code class=\"r\">Perimeter(x = 3)\r\n<\/code><\/pre>\n<pre>## [1] 18.84956\r\n<\/pre>\n<pre><code class=\"r\">Perimeter(x = 5)\r\n<\/code><\/pre>\n<pre>## [1] 31.41593\r\n<\/pre>\n<p><strong>Example<\/strong><\/p>\n<p>Function to compute the area of a rectangle<\/p>\n<pre><code class=\"r\">Area &lt;- function(x,y) {\r\n  x*y\r\n}\r\n\r\nArea(10,7)\r\n<\/code><\/pre>\n<pre>## [1] 70\r\n<\/pre>\n<p><strong>Example<\/strong><\/p>\n<p>Function to compute the area and perimeter of a rectangle<\/p>\n<pre><code class=\"r\">Area.perimeter &lt;- function(x,y) {\r\n  area&lt;-x*y\r\n  perimeter&lt;-2*x+2*y\r\n  return(c(area,perimeter))\r\n}\r\n\r\nArea.perimeter(10,7)\r\n<\/code><\/pre>\n<pre>## [1] 70 34\r\n<\/pre>\n<p>We can specify a default value for a function argument<\/p>\n<p><strong>Example<\/strong><\/p>\n<p>Function to compute the power of a number. The default value is 2 if no value for the power is specified<\/p>\n<pre><code class=\"r\">power &lt;- function(x,n=2) {\r\n  x^n\r\n}\r\n\r\npower(10)\r\n<\/code><\/pre>\n<pre>## [1] 100\r\n<\/pre>\n<pre><code class=\"r\">power(10,3)\r\n<\/code><\/pre>\n<pre>## [1] 1000\r\n<\/pre>\n<p>\u261e Read Section 11 &#8220;Programming tools\u201d from document <a href=\"http:\/\/cran.r-project.org\/doc\/contrib\/Torfs+Brauer-Short-R-Intro.pdf\">\u201cA (very) short introduction to R\u201d<\/a><br \/>\nby P. Torfs and C. Brauer and perform the proposed<br \/>\nexercises in this section<\/p>\n<h3 id=\"toc_58\">Programming tools: if-else statement<\/h3>\n<p><strong>Example<\/strong><\/p>\n<p>The following function contains an if-else statement and provides the absolute value of a number x<\/p>\n<pre><code class=\"r\">absolute.value &lt;- function(x){\r\n    if(x &gt;= 0){\r\n       x\r\n    }\r\n    else{\r\n       -x\r\n    }\r\n}\r\n\r\nabsolute.value(-3.47)\r\n<\/code><\/pre>\n<pre>## [1] 3.47\r\n<\/pre>\n<p>The <code>return()<\/code> statement causes a function to stop executing and returns a value to its caller immediately<\/p>\n<p><strong>Example<\/strong><\/p>\n<p>The following function computes the square root of a number x. It returns a message if the number is negative<\/p>\n<pre><code class=\"r\"> sq.root&lt;- function(x){\r\n    if(x &lt; 0){\r\n       return(\"The number is negative, the square root does not exist. Provide a positive number\")\r\n    }\r\n    else{\r\n       sqrt(x)\r\n    }\r\n}\r\n\r\nsq.root(-3.47)\r\n<\/code><\/pre>\n<pre>## [1] \"The number is negative, the square root does not exist. Provide a positive number\"\r\n<\/pre>\n<p>There is also the function ifelse()<\/p>\n<p><strong>Example<\/strong><\/p>\n<p>Given a variable x, create a categorical variable with values \u201csmall\u201d if x is smaller than the mean and \u201clarge\u201d otherwise:<\/p>\n<pre><code class=\"r\"> catx&lt;- ifelse(x&lt;=mean(x), \"small\", \"large\")\r\n<\/code><\/pre>\n<h3 id=\"toc_59\">Programming tools: for-loop<\/h3>\n<p><strong>Example:<\/strong> The following for-loop prints the first 4 digits<\/p>\n<pre><code class=\"r\">for (i in 1:4){   # Variable i takes values from 1 to 4 consecutively\r\n  print(i)   # at each step of the loop the value of i is printed\r\n}   # end of the for-loop\r\n<\/code><\/pre>\n<pre>## [1] 1\r\n## [1] 2\r\n## [1] 3\r\n## [1] 4\r\n<\/pre>\n<p><strong>Example:<\/strong> The following for-loop prints the names in a list<\/p>\n<pre><code class=\"r\">list.names&lt;-c(\"Alex\", \"John\", \"Mike\")\r\nfor (name in list.names){   # Variable name takes values in list.names\r\n  print(name)   # at each step of the loop the value of name is printed\r\n}   # end of the for-loop\r\n<\/code><\/pre>\n<pre>## [1] \"Alex\"\r\n## [1] \"John\"\r\n## [1] \"Mike\"\r\n<\/pre>\n<p><strong>Example:<\/strong> The following for-loop provides the sum of the first 10 digits<\/p>\n<pre><code class=\"r\">x&lt;-0  # We inicialize at 0 the variable x that will contain the sum\r\nfor (i in 1:10){   # Variable i takes values from 1 to 10 consecutively\r\n  x&lt;-x+i   # at each step of the loop the variable x is incremented by the value of i\r\n}   # end of the for-loop\r\nx   # result: x=sum of the first 10 digits\r\n<\/code><\/pre>\n<pre>## [1] 55\r\n<\/pre>\n<p><strong>Example:<\/strong> The following for-loop performs a t-test on different random generated vectors and returns the vector of p-values<\/p>\n<pre><code class=\"r\">set.seed(123)\r\npvalue.vector&lt;-NULL # We inicialize the vector that will keep the p-values. Using NULL is convenient because we don't need to specify the length nor the data type of the vector\r\nfor (i in 1:5){\r\n  x&lt;-rnorm(n=100, mean=0, sd=1)\r\n  p&lt;-t.test(x, mu=0)$p.value\r\n  pvalue.vector&lt;-c(pvalue.vector,p) # at each step of the loop we add (concatenate with function c()) the new p-value stored in variable p to the output vector pvalue.vector\r\n}   # end of the for-loop\r\n\r\npvalue.vector\r\n<\/code><\/pre>\n<pre>## [1] 0.3243898 0.2687521 0.2076953 0.7280507 0.2872622\r\n<\/pre>\n<p><strong>Example:<\/strong> Generate 100 values from a standard normal distribution and sum up<br \/>\nthose values that are larger than 1.3<\/p>\n<pre><code class=\"r\">s&lt;-0   # We inicialized at 0 the variable s that will contain the sum\r\nfor (i in 1:100){  # Variable i takes values from 1 to 10 consecutively\r\n  x&lt;-rnorm(1,0,1)   # at each step of the loop a value is randomly generated from a normal   distribution with mean=0 and sd=1. The random value is stored in variable x\r\n  if (x&gt;1.3){\r\n    s&lt;-s+x    # at each step of the loop, if x&gt;1.3, the value of s is incremented by x\r\n  }\r\n}   # end of the for-loop\r\ns   # result: s= sum of those random values larger than 1.3\r\n<\/code><\/pre>\n<pre>## [1] 10.74194\r\n<\/pre>\n<p>For and if loops are useful but are computationally not very efficient. You should always think<br \/>\nwhether there is an alternative R code that does not require loops.<\/p>\n<p>The above two examples could be obtained with the following code<\/p>\n<p><strong>Example:<\/strong> Sum of the first 10 digits<\/p>\n<pre><code class=\"r\">i&lt;-seq(1,10,1) # generates the vector i=(1,2,3,...,10)\r\nx&lt;-sum(i)\r\n<\/code><\/pre>\n<p><strong>Example:<\/strong> Generate 100 values from a standard normal distribution and sum up<br \/>\nthose values that are larger than 1.3<\/p>\n<pre><code class=\"r\">x&lt;-rnorm(100,0,1) # x is a vector of length 100 containing random values from a N(0,1) distribution\r\ns&lt;-sum(x[x&gt;1.3])  # sum the values of x that are larger than 1.3\r\n<\/code><\/pre>\n<p>\u261e More info about functions in R:\u00a0<a href=\"https:\/\/www.gastonsanchez.com\/intro2cwd\/functions1.html\" target=\"_blank\" rel=\"noopener\">https:\/\/www.gastonsanchez.com\/intro2cwd\/functions1.html<\/a><\/p>\n<h3 id=\"toc_60\">Avoid loops whenever possible<\/h3>\n<p>R is a vector-oriented language, which often allows us to avoid writing explicit<br \/>\nloops.<\/p>\n<p>Instead of summing two vectors with the following code:<\/p>\n<pre>for (i in 1:length(a)) {\r\n  c[i] = a[i] + b[i]\r\n}\r\n<\/pre>\n<p>R is designed to do all this in a single vectorized operation:<\/p>\n<pre>c = a + b\r\n<\/pre>\n<p>Compare the execution time of these two processes:<\/p>\n<pre>x &lt;- runif(1000000)\r\ny &lt;- runif(1000000)\r\nsystem.time(z &lt;- x + y)\r\nsystem.time(for (i in 1:length(x)) z[i] &lt;- x[i] + y[i])\r\n<\/pre>\n<h3 id=\"toc_61\">Useful functions to avoid loops<\/h3>\n<h4 id=\"toc_62\">Function apply()<\/h4>\n<p><code>apply( )<\/code>: This is a very useful function that avoids using loops in R whenever possible. <code>apply( )<\/code> is used when we want to apply the same function to every row or<br \/>\ncolumn of a matrix.<\/p>\n<p>This function has 3 arguments: arg1=name of the matrix, <code>arg2=1<\/code> if the function is<br \/>\nto be applied to the rows or <code>arg2=2<\/code> if the function is to be applied to the columns, <code>arg3=function<\/code><\/p>\n<p><strong>Example:<\/strong> Assume that x is a matrix of numbers with 4 rows and 3 columns as defined below<\/p>\n<pre><code class=\"r\">x&lt;-matrix(seq(1:12), nrow=4)\r\nx\r\n<\/code><\/pre>\n<pre>##      [,1] [,2] [,3]\r\n## [1,]    1    5    9\r\n## [2,]    2    6   10\r\n## [3,]    3    7   11\r\n## [4,]    4    8   12\r\n<\/pre>\n<pre><code class=\"r\">apply(x,1,mean) # computes the mean of the rows. The result is a vector of length 10\r\n<\/code><\/pre>\n<pre>## [1] 5 6 7 8\r\n<\/pre>\n<pre><code class=\"r\">apply(x,2,mean) # computes the mean of the columns. The result is a vector of length 8\r\n<\/code><\/pre>\n<pre>## [1]  2.5  6.5 10.5\r\n<\/pre>\n<h4 id=\"toc_63\">Function tapply()<\/h4>\n<p><code>tapply(arg1, arg2, fun)<\/code> applies function \u201cfun\u201d to the object \u201carg1\u201d separately for the different groups of indices defined by \u201carg2\u201d<\/p>\n<p><strong><em>Example<\/em><\/strong><\/p>\n<pre><code class=\"r\">y&lt;-c(1, 2, 3, 4, 5, 6, 7, 8)\r\nx&lt;-c(1, 1, 1, 2, 2, 2, 2, 2)\r\n<\/code><\/pre>\n<pre><code class=\"r\">tapply(y, x, sum)  # provides the sum of the elements of y for the two groups defined by x\r\n<\/code><\/pre>\n<pre>##  1  2\r\n##  6 30\r\n<\/pre>\n<p>\u261e Follow: <a href=\"https:\/\/www.datacamp.com\/community\/tutorials\/r-tutorial-apply-family\" target=\"_blank\" rel=\"noopener noreferrer\">Tutorial on the Apply family of functions<\/a><\/p>\n<h2 id=\"toc_64\">Data management with R<\/h2>\n<h3 id=\"toc_65\">Modifying the elements of a numeric or character variable<\/h3>\n<p>With <code>&lt;-<\/code> we can modify the elements of a vector or a matrix<\/p>\n<p><strong>Example<\/strong><\/p>\n<pre><code class=\"r\">A&lt;-c(5, 4, 3, 2, 3)\r\nA[A==3]&lt;-0   # assigns a 0 to the elements of A that are equal to 3\r\nA\r\n<\/code><\/pre>\n<pre>## [1] 5 4 0 2 0\r\n<\/pre>\n<pre><code class=\"r\">B&lt;-c(\"a\", \"a\", \"b\", \"a\", \"b\")\r\nB[B==\"a\"]&lt;-\"c\"    # assigns a \"c\" to the elements of B that are equal to \"a\"\r\nB\r\n<\/code><\/pre>\n<pre>## [1] \"c\" \"c\" \"b\" \"c\" \"b\"\r\n<\/pre>\n<p><strong>Example<\/strong><\/p>\n<pre><code class=\"r\">A&lt;-c(5, 4, 3, 2, 3)\r\nA[A&lt;=3]&lt;-0   # assigns a 0 to the elements of A that are smaller than or equal to 3\r\nA\r\n<\/code><\/pre>\n<pre>## [1] 5 4 0 0 0\r\n<\/pre>\n<p><strong>Example<\/strong> <code>ifelse()<\/code><\/p>\n<pre><code class=\"r\">A&lt;-c(5, 4, 3, 2, 3)\r\nA&lt;-ifelse(A&lt;=3,0,1)   # assigns a 0 to the elements of A that are smaller than or equal to 3 and a 1 to all the other elements\r\nA\r\n<\/code><\/pre>\n<pre>## [1] 1 1 0 0 0\r\n<\/pre>\n<p><strong>Example<\/strong><\/p>\n<pre><code class=\"r\">A&lt;-c(5, 4, 3, 2, 3)\r\nA[(A&lt;3)|(A&gt;4)]&lt;- 0 #assigns a 0 to the elements of A smaller than 3 or larger than 4\r\nA\r\n<\/code><\/pre>\n<pre>## <code class=\"r\">[1] 0 4 3 0 3<\/code><\/pre>\n<h3 id=\"toc_66\">Modifying elements of a factor variable<\/h3>\n<p>If you try to do a similar modification on the values of a factor variable you will obtain a warning.<\/p>\n<p><strong>Example<\/strong><\/p>\n<pre><code class=\"r\">data&lt;-data.frame(\r\n  x=c(25, 23, 31, 42, 36, 24),\r\n  y=c(\"male\", \"female\", \"male\", \"male\", \"female\", \"female\")\r\n  )\r\n<\/code><\/pre>\n<p><strong>Example<\/strong><br \/>\nWe want to change the values in y, \u201cfemale\u201d by \u201cF\u201d and \u201cmale\u201d by \u201cM\u201d<\/p>\n<pre><code class=\"r\">data$y[data$y==\"female\"]&lt;-\"F\"\r\n<\/code><\/pre>\n<pre>## Warning in `[&lt;-.factor`(`*tmp*`, data$y == \"female\", value =\r\n## structure(c(2L, : invalid factor level, NA generated\r\n<\/pre>\n<pre><code class=\"r\">data$y   #  The substitution has not been performed appropriately\r\n<\/code><\/pre>\n<pre>## [1] male &lt;NA&gt; male male &lt;NA&gt; &lt;NA&gt;\r\n## Levels: female male\r\n<\/pre>\n<p>Let&#8217;s read again the data frame data<\/p>\n<pre><code class=\"r\">data&lt;-data.frame(\r\n  x=c(25, 23, 31, 42, 36, 24),\r\n  y=c(\"male\", \"female\", \"male\", \"male\", \"female\", \"female\")\r\n  )\r\ndata\r\n<\/code><\/pre>\n<pre>##    x      y\r\n## 1 25   male\r\n## 2 23 female\r\n## 3 31   male\r\n## 4 42   male\r\n## 5 36 female\r\n## 6 24 female\r\n<\/pre>\n<p>For factor variables we cannot change the values directly, we have to change the levels of the variable:<\/p>\n<pre><code class=\"r\">levels(data$y)\r\n<\/code><\/pre>\n<pre>## [1] \"female\" \"male\"\r\n<\/pre>\n<pre><code class=\"r\">levels(data$y)&lt;-c(\"F\", \"M\")  # We assign an \"F\" to the first level of z and an \"M\" to the second level\r\nlevels(data$y)\r\n<\/code><\/pre>\n<pre>## [1] \"F\" \"M\"\r\n<\/pre>\n<h3 id=\"toc_67\">Modifying the column names<\/h3>\n<p><strong>Example<\/strong><br \/>\nModify the names of the columns of data: \u201cx&#8221;by &#8220;age\u201d and \u201cy\u201d by \u201cgender\u201d<\/p>\n<pre><code class=\"r\">colnames(data)\r\n<\/code><\/pre>\n<pre>## [1] \"x\" \"y\"\r\n<\/pre>\n<pre><code class=\"r\">colnames(data)&lt;-c(\"age\",\"gender\")\r\ncolnames(data)\r\n<\/code><\/pre>\n<pre>## [1] \"age\"    \"gender\"\r\n<\/pre>\n<h3 id=\"toc_68\">Adding and removing columns of a data frame<\/h3>\n<p><strong>Example<\/strong><\/p>\n<pre><code class=\"r\">data$z&lt;-c(1, 2, 3, 4, 5, 6)  # Creates a new variable z in data frame \"data\"\r\ndata\r\n<\/code><\/pre>\n<pre>##   age gender z\r\n## 1  25      M 1\r\n## 2  23      F 2\r\n## 3  31      M 3\r\n## 4  42      M 4\r\n## 5  36      F 5\r\n## 6  24      F 6\r\n<\/pre>\n<pre><code class=\"r\">data$z&lt;-NULL  # Removes variable z from data frame \"data\"\r\ndata\r\n<\/code><\/pre>\n<pre>##   age gender\r\n## 1  25      M\r\n## 2  23      F\r\n## 3  31      M\r\n## 4  42      M\r\n## 5  36      F\r\n## 6  24      F\r\n<\/pre>\n<h3 id=\"toc_69\">Sorting elements<\/h3>\n<p><code>sort()<\/code>, <code>order()<\/code> and <code>rank()<\/code> are important functions for sorting elements<\/p>\n<p><strong>Example<\/strong><\/p>\n<pre><code class=\"r\">x&lt;-c(10, 100, 5)\r\nsort(x)  # provides a new vector with the elements of x rearranged in increasing order\r\n<\/code><\/pre>\n<pre>## [1]   5  10 100\r\n<\/pre>\n<pre><code class=\"r\">sort(x, decreasing = T)  # provides a new vector with the elements of x rearranged in decreasing order\r\n<\/code><\/pre>\n<pre>## [1] 100  10   5\r\n<\/pre>\n<pre><code class=\"r\">order(x)  # returns a vector of indeces for obtaining the ordered vector x\r\n<\/code><\/pre>\n<pre>## [1] 3 1 2\r\n<\/pre>\n<pre><code class=\"r\">x[order(x)]   # this code is equivalent to sort(x)\r\n<\/code><\/pre>\n<pre>## [1]   5  10 100\r\n<\/pre>\n<pre><code class=\"r\">rank(x)  # provides the ranking of the elements in x\r\n<\/code><\/pre>\n<pre>## [1] 2 3 1\r\n<\/pre>\n<p>When ordering vectors in a data frame is more convenient to use the function <code>order()<\/code> because we can retreive the indices and apply the permutation to other variables in the data frame. With <code>sort()<\/code> we don&#8217;t have the information on the permuation applied to the data.<\/p>\n<pre><code class=\"r\">data&lt;-data.frame(\r\n  x=c(25, 23, 31, 42, 36, 24),\r\n  y=c(\"male\", \"female\", \"male\", \"male\", \"female\", \"female\")\r\n  )\r\ndata$x[order(data$x)]   # we obtain the ages in ascending order\r\n<\/code><\/pre>\n<pre>## [1] 23 24 25 31 36 42\r\n<\/pre>\n<pre><code class=\"r\">data$y[order(data$x)]   # we obtain the corresponding gender for each age\r\n<\/code><\/pre>\n<pre>## [1] female female male   male   female male\r\n## Levels: female male\r\n<\/pre>\n<h3 id=\"toc_70\">Missing values<\/h3>\n<p>You can specify any value in a data set as a missing value with the assignment <code>value&lt;-NA<\/code><\/p>\n<p><strong>Example<\/strong><\/p>\n<p>Replace all values equal to 9999 by NA in data frame \u201cdata\u201d<\/p>\n<pre><code class=\"r\">data[data==9999]&lt;-NA\r\n<\/code><\/pre>\n<p><code>is.na()<\/code> provides information about missing values<\/p>\n<p><strong>Example<\/strong><\/p>\n<pre><code class=\"r\">data&lt;-data.frame(\r\n  x=c(25, NA, 31, 42, 36, NA),\r\n  y=c(\"male\", \"female\", NA, \"male\", \"female\", \"female\"),\r\n  z=c(1, 2, 3, 4, 5, 6)\r\n  )\r\n<\/code><\/pre>\n<pre><code class=\"r\">is.na(data$x)   # provides a logical vector indicating which element is missing\r\n<\/code><\/pre>\n<pre>## [1] FALSE  TRUE FALSE FALSE FALSE  TRUE\r\n<\/pre>\n<pre><code class=\"r\">any(is.na(data$x))  # returns TRUE when the vector contains any missing\r\n<\/code><\/pre>\n<pre>## [1] TRUE\r\n<\/pre>\n<pre><code class=\"r\">sum(is.na(data$x))   # provides the number of missing values in a vector\r\n<\/code><\/pre>\n<pre>## [1] 2\r\n<\/pre>\n<pre><code class=\"r\">apply(data, 2, function(x) sum(is.na(x)))  # provides the number of missing values in each column of a data frame\r\n<\/code><\/pre>\n<pre>## x y z\r\n## 2 1 0\r\n<\/pre>\n<p><strong>Example<\/strong><\/p>\n<p>Replace all NA by 0 in data frame \u201cdata\u201d<\/p>\n<pre><code class=\"r\">data[is.na(data)]&lt;-0\r\n<\/code><\/pre>\n<p><code>complete.cases()<\/code> indicate which rows of a data frame contain missing values. It can be used for obtaining a new data frame with only those rows with no missing value<\/p>\n<pre><code class=\"r\">complete.cases(data)   #   Logical indicator of the rows containing or not missing values\r\n<\/code><\/pre>\n<pre>## [1]  TRUE FALSE FALSE  TRUE  TRUE FALSE\r\n<\/pre>\n<pre><code class=\"r\">data[complete.cases(data),]   # new data frame with only those rows with no missing value\r\n<\/code><\/pre>\n<pre>##    x      y z\r\n## 1 25   male 1\r\n## 4 42   male 4\r\n## 5 36 female 5\r\n<\/pre>\n<pre><code class=\"r\">na.omit(data)   # new data frame with only those rows with no missing value\r\n<\/code><\/pre>\n<pre>##    x      y z\r\n## 1 25   male 1\r\n## 4 42   male 4\r\n## 5 36 female 5\r\n<\/pre>\n<h3 id=\"toc_71\">Manipulating strings<\/h3>\n<p><code>grep()<\/code> <code>grep(pattern, x , ignore.case=FALSE, fixed=FALSE)<\/code>: Search for pattern in x. If <code>fixed =FALSE<\/code> then pattern is a <a href=\"http:\/\/regexlib.com\/CheatSheet.aspx?AspxAutoDetectCookieSupport=1\">regular expression<\/a>. If <code>fixed=TRUE<\/code> then pattern is a text string. Returns matching indices.<br \/>\n<strong>Example<\/strong><\/p>\n<pre><code class=\"r\">x&lt;-c(\"male\", \"male\", \"female\", \"female\", \"male\")\r\ngrep(\"female\", x, fixed=TRUE)\r\n<\/code><\/pre>\n<pre>## [1] 3 4\r\n<\/pre>\n<pre><code class=\"r\">grep(\"male\", x, fixed=TRUE)   # all elements in x contains the expression \"male\"\r\n<\/code><\/pre>\n<pre>## [1] 1 2 3 4 5\r\n<\/pre>\n<pre><code class=\"r\">grep(\"^male\", x)  # In regular expression syntax, ^ indicates the start of a string. This code provides those elements in x starting by \"male\"\r\n<\/code><\/pre>\n<pre>## [1] 1 2 5\r\n<\/pre>\n<p><code>paste()<\/code> concatenates characters<\/p>\n<p><strong>Example<\/strong><\/p>\n<pre><code class=\"r\">x&lt;-c(\"male\", \"male\", \"female\", \"female\", \"male\")\r\ny&lt;-c(\"A\", \"A\", \"A\", \"B\", \"B\")\r\nz&lt;-c(1, 2, 3, 4, 5)\r\npaste(x,y,sep=\"-\")\r\n<\/code><\/pre>\n<pre>## [1] \"male-A\"   \"male-A\"   \"female-A\" \"female-B\" \"male-B\"\r\n<\/pre>\n<pre><code class=\"r\">paste(x,z,sep=\".\")\r\n<\/code><\/pre>\n<pre>## [1] \"male.1\"   \"male.2\"   \"female.3\" \"female.4\" \"male.5\"\r\n<\/pre>\n<h3 id=\"toc_72\">Data type conversion<\/h3>\n<p><code>is.<\/code> test the data type:<br \/>\n<code>is.numeric()<\/code>, <code>is.character()<\/code>, <code>is.vector()<\/code>, <code>is.matrix()<\/code>, <code>is.data.frame()<\/code><\/p>\n<p><code>as.<\/code> converts to a data type:<br \/>\n<code>as.numeric()<\/code>, <code>as.character()<\/code>, <code>as.vector()<\/code>, <code>as.matrix()<\/code>, <code>as.data.frame<\/code><\/p>\n<pre><code class=\"r\">x=c(25, 23, 31, 42, 36, 24)\r\n<\/code><\/pre>\n<pre><code class=\"r\">is.numeric(x)\r\n<\/code><\/pre>\n<pre>## [1] TRUE\r\n<\/pre>\n<pre><code class=\"r\">is.character(x)\r\n<\/code><\/pre>\n<pre>## [1] FALSE\r\n<\/pre>\n<pre><code class=\"r\">as.character(x)\r\n<\/code><\/pre>\n<pre>## [1] \"25\" \"23\" \"31\" \"42\" \"36\" \"24\"\r\n<\/pre>\n<pre><code class=\"r\">M&lt;-matrix(1:4, ncol=2)\r\nvectorM&lt;-as.vector(M)\r\nvectorM\r\n<\/code><\/pre>\n<pre>## [1] 1 2 3 4\r\n<\/pre>\n<p>\u261e Follow the tutorial \u201cModifying Data Frames\u201d in <a href=\"http:\/\/gastonsanchez.com\/teaching\/\">http:\/\/gastonsanchez.com\/teaching\/<\/a><\/p>\n<p>\u261e Read sections from <a href=\"http:\/\/www.statmethods.net\/management\/index.html\">http:\/\/www.statmethods.net\/management\/index.html<\/a><\/p>\n<h2 id=\"toc_73\">Workspace<\/h2>\n<p>The workspace is your current R working environment and includes any userdefined objects (vectors, matrices, data frames, lists, functions). At the end of an R<br \/>\nsession, the user can save an image of the current workspace that is automatically<br \/>\nreloaded the next time R is started.<\/p>\n<p><a href=\"http:\/\/www.statmethods.net\/interface\/workspace.html\">http:\/\/www.statmethods.net\/interface\/workspace.html<\/a><\/p>\n<pre><code class=\"r\">save.image()  # save the workspace to the file .RData in the cwd\r\n<\/code><\/pre>\n<pre><code class=\"r\">save(object list,file=\"myfile.RData\")   # save specific objects to a file if you don't specify the path, the current working directory is assumed\r\n<\/code><\/pre>\n<pre><code class=\"r\">load(\"myfile.RData\")  # load a workspace into the current session. Iif you don't specify the path, the cwd is assumed\r\n<\/code><\/pre>\n<pre><code class=\"r\">q() # quit R. You will be prompted to save the workspace.\r\n<\/code><\/pre>\n<h2 id=\"toc_74\">Miscellaneous. Useful functions<\/h2>\n<h3 id=\"toc_75\">Function source()<\/h3>\n<p>You can execute an existing script by using the function <code>source( )<\/code><\/p>\n<pre>source(\"scriptname.R\")\r\n<\/pre>\n<h3 id=\"toc_76\">Function with()<\/h3>\n<p><code>with()<\/code> provides an alternative code for evaluating an R expression in a data frame<\/p>\n<p><strong>Example<\/strong><br \/>\nLet&#8217;s consider the following data frame<\/p>\n<pre><code class=\"r\">example&lt;-data.frame(\r\n  age=c(25, 23, 31, 42, 36, 24),\r\n  gender=c(\"male\", \"female\", \"male\", \"male\", \"female\", \"female\")\r\n  )\r\n<\/code><\/pre>\n<p>The usual code for obtaining the mean of variable \u201cage\u201d is<\/p>\n<pre><code class=\"r\">mean(example$age)\r\n<\/code><\/pre>\n<pre>## [1] 30.16667\r\n<\/pre>\n<p>The alternative code using function <code>with()<\/code> is<\/p>\n<pre><code class=\"r\">with(example, mean(age))\r\n<\/code><\/pre>\n<pre>## [1] 30.16667\r\n<\/pre>\n<p>The usual code for obtaining the mean of variable \u201cage\u201d separately by gender is<\/p>\n<pre><code class=\"r\">tapply(example$age, example$gender, mean)\r\n<\/code><\/pre>\n<pre>##   female     male\r\n## 27.66667 32.66667\r\n<\/pre>\n<p>The alternative code using function <code>with()<\/code> is<\/p>\n<pre><code class=\"r\">with(example, tapply(age, gender, mean))\r\n<\/code><\/pre>\n<pre>##   female     male\r\n## 27.66667 32.66667\r\n<\/pre>\n<h3 id=\"toc_77\">Function which()<\/h3>\n<p><code>which()<\/code> gives the indices that satisfie a logical expression<\/p>\n<p><strong>Example<\/strong><\/p>\n<pre><code class=\"r\">  age=c(25, 23, 31, 42, 36, 24)\r\n<\/code><\/pre>\n<pre><code class=\"r\">which(age&gt;30)   # indices of those elements in \"age\" larger than 30\r\n<\/code><\/pre>\n<pre>## [1] 3 4 5\r\n<\/pre>\n<h3 id=\"toc_78\">Function list.files()<\/h3>\n<p>This function is useful when working with multiple data files.<\/p>\n<p><code>list.files()<\/code> returns every file in the current working directory<\/p>\n<p><code>list.files(path=\".\", pattern=NULL)<\/code> The first argument, path, specifies the path to the directory to be searched, by default the current working directory, and the second argument, pattern, specifies a pattern in the names of the files. If no pattern is specified all files are returned.<\/p>\n<p><strong>Example<\/strong><\/p>\n<p>In this example we store the names of all csv files in an object called \u201cfiles_csv\u201d<\/p>\n<pre><code class=\"r\">files_csv&lt;-list.files(pattern=\"csv\")\r\n<\/code><\/pre>\n<h3 id=\"toc_79\">Function sessionInfo()<\/h3>\n<p><code>sessionInfo()<\/code>provides the version of R you are running, the type of computer you are using and the versions of the packages that have been loaded.<\/p>\n<h3 id=\"toc_80\">The stringsAsFactors and as.is arguments<\/h3>\n<p>The default behavior of R when reading a data set, with for instance <code>read.csv()<\/code>, is to convert character strings into factors. In some situations this is not convenient and you can avoid this conversion by specifying the argument <code>stringsAsFactors=F<\/code> within function <code>read.csv()<\/code>.<\/p>\n<p>If you just want to prevent the conversion from string to factor of a specific column n you can specify the argument <code>as.is=n<\/code> where n is the number of the column that you want to keep as a string.<\/p>\n<p><strong>Example<\/strong><\/p>\n<pre><code class=\"r\">data&lt;-read.csv(\"file.csv\", header=T, stringsAsFactors = F)  # prevents the conversion of all string columns to factor\r\n\r\ndata&lt;-read.csv(\"file.csv\", header=T, as.is=3)  # prevents the conversion of column 3 from string to factor\r\n<\/code><\/pre>\n<h3 id=\"toc_81\">attach() and detach()<\/h3>\n<p>The <code>attach()<\/code> specifies the data frame to be used and variables in the data frame can be accessed by simply giving their names<\/p>\n<p>Function <code>detach()<\/code> removes the attachment<\/p>\n<p><strong>Example<\/strong><\/p>\n<p>You want to calculate the mean of a variable \u201cx\u201d\u201c in a data frame called &#8220;data\u201d. You usually will execute <code>mean(data$x)<\/code>. Instead, you can also execute:<\/p>\n<pre><code class=\"r\">attach(data)\r\nmean(x)  # Since data frame \"data\" is attached you don't need to specify the variable as data$x but only by x\r\n\r\ndetach(data)\r\n<\/code><\/pre>\n<p>Though attach() may seem to be a very useful function since it saves us from typing the name of the data frame, it should be used with caution since it may give errors if it is easy to call it is called repeatedly without the call of detach(). These functions should be avoided within functions.<\/p>\n<h2 id=\"toc_82\">Documentation<\/h2>\n<p><strong>Interesting references:<\/strong><\/p>\n<p><a href=\"http:\/\/www.r-tutor.com\/\">R Tutorial. An R Introduction to Statistics<\/a><\/p>\n<p><a href=\"http:\/\/www.statmethods.net\/index.html\">QUICK-R<\/a><\/p>\n<p><a href=\"http:\/\/www.cookbook-r.com\/\">Cookbook for R<\/a><\/p>\n<p><a href=\"http:\/\/gastonsanchez.com\/blog\/\">Gaston Sanchez blog<\/a><\/p>\n<p><a href=\"https:\/\/cran.r-project.org\/doc\/manuals\/r-release\/R-intro.html\">An Introduction to R from R Development Core Team<\/a><\/p>\n<p><a href=\"https:\/\/sites.google.com\/a\/bioinformatics.ucr.edu\/bioinformatics-manuals\/home\/programming-in-r\">Programming in R by T.Girke<\/a><\/p>\n<p><a href=\"http:\/\/manuals.bioinformatics.ucr.edu\/home\/R_BioCondManual\">R &amp; Bioconductor by T.Girke<\/a><\/p>\n<hr \/>\n<p>This document was created with R Markdown: <a href=\"http:\/\/rmarkdown.rstudio.com\/\">http:\/\/rmarkdown.rstudio.com\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Table of Contents\u00a0\u00a0 Installation: R and Rstudio Using scripts Simple computations with R R functions Help and documentation List and &hellip; <a href=\"https:\/\/mon.uvic.cat\/statistical-pills\/introduction-to-r\/\">Read More<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-5","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/mon.uvic.cat\/statistical-pills\/wp-json\/wp\/v2\/pages\/5","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mon.uvic.cat\/statistical-pills\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/mon.uvic.cat\/statistical-pills\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/mon.uvic.cat\/statistical-pills\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mon.uvic.cat\/statistical-pills\/wp-json\/wp\/v2\/comments?post=5"}],"version-history":[{"count":29,"href":"https:\/\/mon.uvic.cat\/statistical-pills\/wp-json\/wp\/v2\/pages\/5\/revisions"}],"predecessor-version":[{"id":865,"href":"https:\/\/mon.uvic.cat\/statistical-pills\/wp-json\/wp\/v2\/pages\/5\/revisions\/865"}],"wp:attachment":[{"href":"https:\/\/mon.uvic.cat\/statistical-pills\/wp-json\/wp\/v2\/media?parent=5"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}