<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/r-101-2/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://feedproxy.google.com/~r/LIBDrstats/~3/v5zVQwZUdnM/"> rstats on LIBD rstats club</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<div>
<h3>HAPPY HOLIDAYS!!!<img alt="🎉" src="https://s.w.org/images/core/emoji/2.4/72x72/1f389.png" class="wp-smiley"><img alt="⛄" src="https://s.w.org/images/core/emoji/2.4/72x72/26c4.png" class="wp-smiley"><img alt="🎆" src="https://s.w.org/images/core/emoji/2.4/72x72/1f386.png" class="wp-smiley"><img alt="🍾" src="https://s.w.org/images/core/emoji/2.4/72x72/1f37e.png" class="wp-smiley"><img alt="❄" src="https://s.w.org/images/core/emoji/2.4/72x72/2744.png" class="wp-smiley"></h3>
<p>In the spirit of the coming new year and new beginnings, we created a tutorial for getting started or restarted with R. If you are new to R or have dabbled in R but haven’t used it much recently, then this post is for you. We will focus on data classes and types, as well as data wrangling, and we will provide basic statistics and basic plotting examples using real data. Enjoy!</p>
<p>By <a rel="nofollow" href="https://carriewright11.github.io/" target="_blank">C.Wright</a></p>
<p>As with most programming tutorials, let’s start with a good’ol “Hello World”.</p>
<div>
<h6>1) First Command</h6>
<pre><code>print(&quot;Hello World&quot;)</code></pre>
<pre><code>## [1] &quot;Hello World&quot;</code></pre>
</div>
<div>
<h6>2) Install and Load Packages and Data</h6>
<p>Now we need some data. Packages are collections of functions and/or data. There are published packages that you can use from the community such as these two packages, or you can make your own package for your own private use.</p>
<pre><code>install.packages(&quot;babynames&quot;)  
install.packages(&quot;titanic&quot;)</code></pre>
<p>Now that we have installed the packages, we need to load them.</p>
<pre><code>library(&quot;babynames&quot;)
library(&quot;titanic&quot;)</code></pre>
<p>Each installation of R comes with quite a bit of data! Now we want to load the “quake” data – there are lots of other options.</p>
<pre><code>data(&quot;quakes&quot;)
data() #this will list all of the datasets available</code></pre>
</div>
<div>
<h6>3) Assigning Objects</h6>
<p>Objects can be many different things ranging from a simple number to a giant matrix, but they refer to things that you can manipulate in R.</p>
<pre><code>myString &lt;- &quot;Hello World&quot; #notice how we need &quot;&quot; around words, aka strings
myString #take a look at myString</code></pre>
<pre><code>## [1] &quot;Hello World&quot;</code></pre>
<pre><code>A &lt;- 14 #now we do not need &quot;&quot; around numbers
A #take a look at A</code></pre>
<pre><code>## [1] 14</code></pre>
<pre><code>A = 5 #can also use the equal sign to assign objects
A #notice how A has changed</code></pre>
<pre><code>## [1] 5</code></pre>
</div>
<div>
<h6>4) Assigning Objects with Multiple Elements</h6>
<p>Now lets assign a more complex object</p>
<pre><code>height &lt;- c(5.5, 4.5, 5, 5.6, 5.8, 5.2, 6, 6.2, 5.9, 5.8, 6, 5.9) #this is called a vector
colors_to_use &lt;- c(&quot;red&quot;, &quot;blue&quot;)# a vector of strings</code></pre>
</div>
<div>
<h6>5) Classes</h6>
<p>There are a variety of different object classes. We can use the function class() to tell us what class an object belongs to.</p>
<pre><code>class(height) #this is a numeric vector</code></pre>
<pre><code>## [1] &quot;numeric&quot;</code></pre>
<pre><code>class(colors_to_use) #this is a character vector</code></pre>
<pre><code>## [1] &quot;character&quot;</code></pre>
<pre><code>heightdf&lt;-data.frame(height, gender =c(&quot;F&quot;, &quot;F&quot;, &quot;F&quot;, &quot;F&quot;, &quot;F&quot;, &quot;F&quot;, &quot;M&quot;, &quot;M&quot;, &quot;M&quot;, &quot;M&quot;, &quot;M&quot;, &quot;M&quot;))
heightdf #take a look at the dataframe</code></pre>
<pre><code>##    height gender
## 1     5.5      F
## 2     4.5      F
## 3     5.0      F
## 4     5.6      F
## 5     5.8      F
## 6     5.2      F
## 7     6.0      M
## 8     6.2      M
## 9     5.9      M
## 10    5.8      M
## 11    6.0      M
## 12    5.9      M</code></pre>
<pre><code>class(heightdf) #check the class</code></pre>
<pre><code>## [1] &quot;data.frame&quot;</code></pre>
<pre><code>heightdf$height # we can refer to indivdual columns based on the column name</code></pre>
<pre><code>##  [1] 5.5 4.5 5.0 5.6 5.8 5.2 6.0 6.2 5.9 5.8 6.0 5.9</code></pre>
<pre><code>class(heightdf$gender)#here we see a factor(categorical variable - stored in R as with integer levels</code></pre>
<pre><code>## [1] &quot;factor&quot;</code></pre>
<pre><code>logical_variable&lt;-height == heightdf$height #this shows that all the elements in the height column of the heightdf dataframe are equivalent to those of the height vector
class(logical_variable)</code></pre>
<pre><code>## [1] &quot;logical&quot;</code></pre>
<pre><code>matrix_variable &lt;- matrix(height, nrow = 2, ncol = 3)#now we will make a matrix
matrix_variable #take a look at the matrix</code></pre>
<pre><code>##      [,1] [,2] [,3]
## [1,]  5.5  5.0  5.8
## [2,]  4.5  5.6  5.2</code></pre>
<pre><code>class(matrix_variable)</code></pre>
<pre><code>## [1] &quot;matrix&quot;</code></pre>
</div>
<div>
<h6>6) Subsetting Data</h6>
<p>Now that we can assign or instantiate objects, let’s try to look at or manipulate specific parts of more complex objects.</p>
<p>Lets create an object of male heights by grabbing rows from heightdf.</p>
<pre><code>maleIndex&lt;-which(heightdf$gender == &quot;M&quot;) #lets try subsetting just the male data out of the heightdf - first we need to determine which rows of the dataframe are male
maleIndex # this is now just a list of rows</code></pre>
<pre><code>## [1]  7  8  9 10 11 12</code></pre>
<pre><code>heightmale&lt;-heightdf[maleIndex,] #now we will use the brackets to grab these rows - we use the comma to indicate that we want rows not columns
heightmale # now this is just the males</code></pre>
<pre><code>##    height gender
## 7     6.0      M
## 8     6.2      M
## 9     5.9      M
## 10    5.8      M
## 11    6.0      M
## 12    5.9      M</code></pre>
<p>Here is another way using a package called dpylr:</p>
<pre><code>install.packages(&quot;dplyr&quot;)</code></pre>
<p>Here we are creating an object of height data for males over 6 feet.</p>
<pre><code>library(dplyr) #load a useful package for subsetting data</code></pre>
<pre><code>## 
## Attaching package: 'dplyr'</code></pre>
<pre><code>## The following objects are masked from 'package:stats':
## 
##     filter, lag</code></pre>
<pre><code>## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union</code></pre>
<pre><code>#heightmale_over6feet &lt;- dplyr::subset(heightdf, gender ==&quot;M&quot; &amp; height >=6)#need to use column names to describe what we want to pull out of our data
heightmale_over6feet &lt;- subset(heightdf, gender ==&quot;M&quot; &amp; height >=6)#need to use column names to describe what we want to pull out of our data

heightmale_over6feet#now we just have the males 6 feet or over</code></pre>
<pre><code>##    height gender
## 7     6.0      M
## 8     6.2      M
## 11    6.0      M</code></pre>
<p>Now let’s create an object by grabbing part of an object based on its columns.</p>
<pre><code>gender1&lt;-heightdf[2]#notice how here we use the brackets but no comma
gender1</code></pre>
<pre><code>##    gender
## 1       F
## 2       F
## 3       F
## 4       F
## 5       F
## 6       F
## 7       M
## 8       M
## 9       M
## 10      M
## 11      M
## 12      M</code></pre>
<pre><code>gender2&lt;-heightdf$gender#this does the same thing #notice this way we loose the data architecture - no longer a dataframe
gender2</code></pre>
<pre><code>##  [1] F F F F F F M M M M M M
## Levels: F M</code></pre>
<pre><code>gender2&lt;-data.frame(gender =heightdf$gender)# this however stays as a dataframe
gender2</code></pre>
<pre><code>##    gender
## 1       F
## 2       F
## 3       F
## 4       F
## 5       F
## 6       F
## 7       M
## 8       M
## 9       M
## 10      M
## 11      M
## 12      M</code></pre>
<pre><code>genderindex&lt;- which(colnames(heightdf) == &quot;gender&quot;) #now wwe will use which() to select columns named gender
genderindex</code></pre>
<pre><code>## [1] 2</code></pre>
<pre><code>gender3 &lt;-heightdf[genderindex]#now we will use the brackets to grab just this column
gender3</code></pre>
<pre><code>##    gender
## 1       F
## 2       F
## 3       F
## 4       F
## 5       F
## 6       F
## 7       M
## 8       M
## 9       M
## 10      M
## 11      M
## 12      M</code></pre>
<pre><code>identical(gender1, gender2)#lets see if they are identical - this is a helpful function - can only compare two variables at a time</code></pre>
<pre><code>## [1] TRUE</code></pre>
<pre><code>gender1==gender2 # are they the same? should say true if they are</code></pre>
<pre><code>##       gender
##  [1,]   TRUE
##  [2,]   TRUE
##  [3,]   TRUE
##  [4,]   TRUE
##  [5,]   TRUE
##  [6,]   TRUE
##  [7,]   TRUE
##  [8,]   TRUE
##  [9,]   TRUE
## [10,]   TRUE
## [11,]   TRUE
## [12,]   TRUE</code></pre>
<pre><code>gender2==gender3 # are they the same? should say true if they are</code></pre>
<pre><code>##       gender
##  [1,]   TRUE
##  [2,]   TRUE
##  [3,]   TRUE
##  [4,]   TRUE
##  [5,]   TRUE
##  [6,]   TRUE
##  [7,]   TRUE
##  [8,]   TRUE
##  [9,]   TRUE
## [10,]   TRUE
## [11,]   TRUE
## [12,]   TRUE</code></pre>
<p>Now let’s try to look at/grab specific values.</p>
<pre><code>height2&lt;-c(6, 5.5, 6, 6, 6, 6, 4.3) #6 and 5.5 are in our orignal height vector but not 4.3
which(height %in% height2) # what of our orignial data is also found in height2</code></pre>
<pre><code>## [1]  1  7 11</code></pre>
<pre><code>heightdf[which(height %in% height2),] # here we skipped making another variable for the index</code></pre>
<pre><code>##    height gender
## 1     5.5      F
## 7     6.0      M
## 11    6.0      M</code></pre>
<pre><code>#we can also use a function clalled grep
wanted_heights_index&lt;-grep(5.9, heightdf$height)
heightdf[wanted_heights_index,] #now we just have the samples who are 5.9</code></pre>
<pre><code>##    height gender
## 9     5.9      M
## 12    5.9      M</code></pre>
<pre><code>#say we want to know the value of an element at a particular location
heightdf$height[2] #second value in the height column</code></pre>
<pre><code>## [1] 4.5</code></pre>
<pre><code>heightdf$height[1:3]# first three valeus in the height column</code></pre>
<pre><code>## [1] 5.5 4.5 5.0</code></pre>
<p>This allows you to grab random data points.</p>
<pre><code>sample(heightdf$height, 2)#takes a random sample from a vector of the specified number of elements</code></pre>
<pre><code>## [1] 5.5 5.9</code></pre>
<pre><code>sample.int(1000999, 2)#takes a random sample from 1 to the first whole number specified. Thue number of random values to output is given by the second number.</code></pre>
<pre><code>## [1] 161093 430020</code></pre>
</div>
<div>
<h6>7) Plotting Data</h6>
<p>Now let’s try plotting some data and perform some statistical tests.</p>
<pre><code>boxplot(heightdf$height~heightdf$gender)#simple boxplot</code></pre>
<p><img src="https://i0.wp.com/lieberinstitute.github.io/rstatsclub/post/2018-12-24-R_101_files/figure-html/unnamed-chunk-14-1.png?w=450" data-recalc-dims="1"></p>
<pre><code>#lets make a fancy boxplot
boxplot(heightdf$height~heightdf$gender, col = c(&quot;red&quot;, &quot;blue&quot;), ylab = &quot;Height&quot;, xlab = &quot;Gender&quot;, main = &quot;Relationship of gender and height&quot;, cex.lab =2, cex.main = 2, cex.axis = 1.3, par(mar=c(5, 5, 5, 5)))</code></pre>
<p><img src="https://i2.wp.com/lieberinstitute.github.io/rstatsclub/post/2018-12-24-R_101_files/figure-html/unnamed-chunk-14-2.png?w=450" data-recalc-dims="1"></p>
<pre><code>hist(heightdf$height)#histogram</code></pre>
<p><img src="https://i0.wp.com/lieberinstitute.github.io/rstatsclub/post/2018-12-24-R_101_files/figure-html/unnamed-chunk-14-3.png?w=450" data-recalc-dims="1"></p>
<pre><code>heightdf$age &lt;-c(20, 30, 15, 20, 40, 14, 35, 40, 17, 16, 25, 16)##adding another variable to a dataframe
plot(heightdf$height)#one variable</code></pre>
<p><img src="https://i2.wp.com/lieberinstitute.github.io/rstatsclub/post/2018-12-24-R_101_files/figure-html/unnamed-chunk-14-4.png?w=450" data-recalc-dims="1"></p>
<pre><code>plot(y=heightdf$height, x=heightdf$age)#scatterplot of 2 variables
height_age&lt;-lm(heightdf$height~heightdf$age)#perform a regression on the data - evaluate height and age relationship
summary(height_age)#shows the stats results from the regression</code></pre>
<pre><code>## 
## Call:
## lm(formula = heightdf$height ~ heightdf$age)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -1.1999 -0.1154  0.1348  0.3634  0.3943 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   5.28384    0.39367  13.422 1.01e-07 ***
## heightdf$age  0.01387    0.01527   0.908    0.385    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.4973 on 10 degrees of freedom
## Multiple R-squared:  0.07616,    Adjusted R-squared:  -0.01622 
## F-statistic: 0.8244 on 1 and 10 DF,  p-value: 0.3853</code></pre>
<pre><code>abline(height_age)#add regression line to plot</code></pre>
<p><img src="https://i2.wp.com/lieberinstitute.github.io/rstatsclub/post/2018-12-24-R_101_files/figure-html/unnamed-chunk-14-5.png?w=450" data-recalc-dims="1"></p>
<pre><code>cor.test(y=heightdf$height, x=heightdf$age)#shows the same p value when performing a correlation test</code></pre>
<pre><code>## 
##  Pearson's product-moment correlation
## 
## data:  heightdf$age and heightdf$height
## t = 0.90797, df = 10, p-value = 0.3853
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  -0.3539944  0.7336745
## sample estimates:
##       cor 
## 0.2759734</code></pre>
</div>
<div>
<h6>8) More Statistical Tests</h6>
<pre><code>t.test(heightdf$height~heightdf$gender)#try a t test between male height and female height - this is significant!</code></pre>
<pre><code>## 
##  Welch Two Sample t-test
## 
## data:  heightdf$height by heightdf$gender
## t = -3.4903, df = 5.8325, p-value = 0.01359
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
##  -1.194177 -0.205823
## sample estimates:
## mean in group F mean in group M 
##        5.266667        5.966667</code></pre>
<pre><code>#if p&lt;0.05 it is generally considered significant
fit &lt;-aov(heightdf$height~heightdf$gender + heightdf$age)#now lets perform an anova or multiple regression
summary(fit)# here are the results</code></pre>
<pre><code>##                 Df Sum Sq Mean Sq F value  Pr(>F)   
## heightdf$gender  1 1.4700  1.4700  12.167 0.00685 **
## heightdf$age     1 0.1193  0.1193   0.987 0.34638   
## Residuals        9 1.0874  0.1208                   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1</code></pre>
<pre><code>anova(fit)# same results</code></pre>
<pre><code>## Analysis of Variance Table
## 
## Response: heightdf$height
##                 Df  Sum Sq Mean Sq F value   Pr(>F)   
## heightdf$gender  1 1.47000 1.47000 12.1668 0.006851 **
## heightdf$age     1 0.11928 0.11928  0.9872 0.346383   
## Residuals        9 1.08739 0.12082                    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1</code></pre>
<pre><code>fit &lt;-lm(heightdf$height~heightdf$gender + heightdf$age)# performing as multiple regression
summary(fit) #gives the same result as above - this is an anova but the results are presented differently</code></pre>
<pre><code>## 
## Call:
## lm(formula = heightdf$height ~ heightdf$gender + heightdf$age)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.83944 -0.07318  0.02918  0.12062  0.36706 
## 
## Coefficients:
##                  Estimate Std. Error t value Pr(>|t|)    
## (Intercept)       5.01995    0.28600  17.552 2.86e-08 ***
## heightdf$genderM  0.68225    0.20148   3.386  0.00805 ** 
## heightdf$age      0.01065    0.01072   0.994  0.34638    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.3476 on 9 degrees of freedom
## Multiple R-squared:  0.5938, Adjusted R-squared:  0.5035 
## F-statistic: 6.577 on 2 and 9 DF,  p-value: 0.01736</code></pre>
<pre><code>anova(fit)#also gives the same result</code></pre>
<pre><code>## Analysis of Variance Table
## 
## Response: heightdf$height
##                 Df  Sum Sq Mean Sq F value   Pr(>F)   
## heightdf$gender  1 1.47000 1.47000 12.1668 0.006851 **
## heightdf$age     1 0.11928 0.11928  0.9872 0.346383   
## Residuals        9 1.08739 0.12082                    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1</code></pre>
<p>Let’s do a more classic anova – using a categorical variable with more than two categories.</p>
<pre><code>heightdf$country &lt;-c(&quot;British&quot;, &quot;French&quot;, &quot;British&quot;, &quot;Dutch&quot;, &quot;Dutch&quot;, &quot;French&quot;, &quot;Dutch&quot;, &quot;Dutch&quot;, &quot;British&quot;, &quot;French&quot;, &quot;British&quot;, &quot;French&quot;)
fit &lt;-aov(heightdf$height~heightdf$gender + heightdf$age + heightdf$country)
summary(fit)</code></pre>
<pre><code>##                  Df Sum Sq Mean Sq F value  Pr(>F)   
## heightdf$gender   1 1.4700  1.4700  19.157 0.00325 **
## heightdf$age      1 0.1193  0.1193   1.554 0.25258   
## heightdf$country  2 0.5503  0.2751   3.586 0.08471 . 
## Residuals         7 0.5371  0.0767                   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1</code></pre>
<pre><code>fit &lt;-aov(heightdf$height~ heightdf$country)
summary(fit)</code></pre>
<pre><code>##                  Df Sum Sq Mean Sq F value Pr(>F)
## heightdf$country  2 0.6067  0.3033   1.319  0.315
## Residuals         9 2.0700  0.2300</code></pre>
<pre><code>anova(fit)# we see the results of country but not each country</code></pre>
<pre><code>## Analysis of Variance Table
## 
## Response: heightdf$height
##                  Df  Sum Sq Mean Sq F value Pr(>F)
## heightdf$country  2 0.60667 0.30333  1.3188 0.3146
## Residuals         9 2.07000 0.23000</code></pre>
<pre><code>TukeyHSD(fit)# this is how we get these results - none are significant</code></pre>
<pre><code>##   Tukey multiple comparisons of means
##     95% family-wise confidence level
## 
## Fit: aov(formula = heightdf$height ~ heightdf$country)
## 
## $`heightdf$country`
##                 diff        lwr       upr     p adj
## Dutch-British   0.30 -0.6468152 1.2468152 0.6627841
## French-British -0.25 -1.1968152 0.6968152 0.7484769
## French-Dutch   -0.55 -1.4968152 0.3968152 0.2860337</code></pre>
<pre><code>fit &lt;-lm(heightdf$height~heightdf$gender + heightdf$age + heightdf$country)
summary(fit) #gives the same result as above - this is an anova just different output</code></pre>
<pre><code>## 
## Call:
## lm(formula = heightdf$height ~ heightdf$gender + heightdf$age + 
##     heightdf$country)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.36474 -0.13454  0.03405  0.15333  0.33097 
## 
## Coefficients:
##                        Estimate Std. Error t value Pr(>|t|)    
## (Intercept)             5.46051    0.28225  19.346 2.46e-07 ***
## heightdf$genderM        0.71905    0.16131   4.458  0.00294 ** 
## heightdf$age           -0.01143    0.01263  -0.905  0.39547    
## heightdf$countryDutch   0.46574    0.26813   1.737  0.12596    
## heightdf$countryFrench -0.25286    0.19590  -1.291  0.23778    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.277 on 7 degrees of freedom
## Multiple R-squared:  0.7993, Adjusted R-squared:  0.6847 
## F-statistic: 6.971 on 4 and 7 DF,  p-value: 0.01375</code></pre>
</div>
</div>
<div>
<h3>Lets use some <strong>real</strong> data!</h3>
<div>
<h6>Baby Name Data</h6>
<p>This is a very fun package to check out. If you have ever wondered about the popularity of your name or someone that you know, you will find this very interesting. I also have some friends who have used it to help them name their child.</p>
<pre><code>#recall that we installed and loaded this data earlier
head(babynames)#this is a special data type called a tibble - it is basically a fancy dataframe</code></pre>
<pre><code>## # A tibble: 6 x 5
##    year sex   name          n   prop
##   </code></pre></div></div>