<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="http://www.r-bloggers.com/r-for-publication-by-page-piccinini-lesson-2-linear-regression/"></div></div><div><a data-url="http://www.r-bloggers.com/r-for-publication-by-page-piccinini-lesson-2-linear-regression/" data-counturl="http://www.r-bloggers.com/r-for-publication-by-page-piccinini-lesson-2-linear-regression/" data-count="horizontal" data-text="R for Publication by Page Piccinini: Lesson 2 – Linear Regression" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://datascienceplus.com/r-for-publication-by-page-piccinini-lesson-2-linear-regression/"> DataScience+</a></strong>, and kindly contributed to <a rel="nofollow" href="http://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>This is our first lesson where we actually learn and use a new statistic in R. For today’s lesson we’ll be focusing on linear regression. I’ll be taking for granted some of the set-up steps from <a target="_blank" href="http://datascienceplus.com/r-for-publication-by-page-piccinini-lesson-1-r-basics/">Lesson 1</a>, so if you haven’t done that yet be sure to go back and do it.</p>
<p>By the end of this lesson you will:</p>
<blockquote><ul>
<li>Have learned the math of linear regression.</li>
<li>Be able to make figures to present data for a linear regression.</li>
<li>Be able to run a linear regression and interpret the results.</li>
<li>Have an R Markdown document to summarize the lesson.</li>

</ul>
<p>There is a video in end of this post which provides the background on the math of linear regression and introduces the data set we’ll be using today. For all of the coding please see the text below. A PDF of the slides can be downloaded <a target="_blank" href="http://datascienceplus.com/wp-content/uploads/2016/05/rcourse_lesson2.pdf">here</a>. Before beginning please download <a target="_blank" rel="nofollow" href="https://github.com/pagepiccinini/rcourse_lesson1/blob/master/data/rcourse_lesson1_data.txt">this text file</a>, it is the data we will use for the lesson. We’ll be using data from the United States of America Social Security Administration on baby names acquired from the R package <code>babynames</code>. All of the data and completed code for the lesson can be found on my <a target="_blank" rel="nofollow" href="https://github.com/pagepiccinini/rcourse_lesson2">github account</a>.</p>
<h2>Lab Problem</h2>
<p>As mentioned, the lab portion of the lesson uses data from the USA Social Security Administration on baby names. We’ll be testing two questions using linear regression, one with a continuous predictor and one with a categorical predictor. <em>Continuous Predictor:</em> Does your name get more or less popular between the years of 1901 and 2000? <em>Categorical Predictor:</em> Is your name more or less popular with females or males?</p>
<h2>Setting up Your Work Space</h2>
<p>As we did for <a target="_blank" href="http://datascienceplus.com/r-for-publication-by-page-piccinini-lesson-1-r-basics/">Lesson 1</a> complete the following steps to create your work space. If you want more details on how to do this refer back to Lesson 1:</p>
<blockquote><ul>
<li>Make your directory (e.g. “rcourse_lesson2”) with folders inside (e.g. “data”, “figures”, “scripts”, “write_up”).</li>
<li>Put the data file for this lesson in your “data” folder.</li>
<li>Make an R Project based in your main directory folder (e.g. “rcourse_lesson2”).</li>
<li>Commit to Git.</li>
<li>Create the repository on Bitbucket and push your initial commit to Bitbucket.</li>

</ul>
<p>Okay you’re all ready to get started!</p>
<h2>Cleaning Script</h2>
<p>One thing I find to be very useful is to have separate scripts for each part of my coding in R. I’ve distilled this down to three scripts: 1) cleaning, 2) figures, and 3) statistics. For most projects these are the only scripts I need. We’ll use that system today and we’ll start with the basis of it all, the cleaning script.</p>
<p>Make a new script from the menu. We start the same way we did last time, by having a header line talking about loading any necessary packages. This time though we’ll only be loading <code>dplyr</code>, not <code>ggplot2</code> (that will come in later during our figures script). Copy the code below and run it.</p>
<pre>## LOAD PACKAGES ####
library(dplyr)</pre>
<p>Also like last time we’ll read in our data from our data folder. This call is the same as Lesson 1, just calling in a different file. Copy the code below and run it.</p>
<pre>## READ IN DATA ####
data = read.table(&quot;data/rcourse_lesson2_data.txt&quot;, header=T, sep=&quot;t&quot;)</pre>
<p>If you want to double check that everything read in correctly take a <code>dim()</code> or a <code>head()</code> of the data frame. You should have 1,792,091 rows and 5 columns. This is all of the baby names with at least five appearances in a year for girls and boys from 1880 to 2013. Today we’ll be focusing on one specific name, yours. For the lesson I’ll be using my name but feel free to use your own. To focus on just one name we’ll need to do a <code>filter()</code> call. This is where my data cleaning begins. In the code below I filter the data frame to only include my name “Page”. Copy the code below and run it with your own name.</p>
<pre>## CLEAN DATA ####
data_clean = data %>%
             filter(name == &quot;Page&quot;)</pre>
<p>To double check that worked call a <code>head()</code> on “data_clean”.</p>
<pre>head(data_clean)</pre>
<p>If it worked you should see only your name in the “name” column. If you see other names it means something is wrong, and you should double check the code. If you see nothing except for the column names it means your name does not exist in the data set. Pick a different name to use for the lesson and run the code again. When you find a name that works move to the next step.</p>
<p>Another way to check if you only have one name in “data_clean” is to call an <code>xtabs()</code> call like the one below. In theory all the data points should be in one cell, in my case the cell for “Page”.</p>
<pre>xtabs(~name, data_clean)</pre>
<p>You may notice though that R stops printing out all of the empty cells after a while, for me even before getting to “Page”. This is because even when you filter out a level of a variable the data frame still remembers it used to be there, and notes that there are currently 0 instances of it. To get rid of this we’re going to add a second line to our “data_clean” chuck using a new <code>dplyr</code> verb, <code>mutate()</code>. Copy and run the updated code below.</p>
<pre>data_clean = data %>%
             filter(name == &quot;Page&quot;) %>%
             mutate(name = factor(name))</pre>
<p>The <code>mutate()</code> verb is used to make a new column or change an existing one. In our case we’re changing the existing column “name” to have it recreate the levels to only include the ones after our <code>filter()</code> call, that’s what the <code>factor()</code> function does for us here. Now if you call the <code>xtabs()</code> call from above you should only see one cell, your name, with the number of data points in “data_clean”.</p>
<p>We have two more updates we’re going to make to “data_clean” before we finish with our cleaning script (for now at least). Instead of looking at all years we’re only going to look at the years between 1901 and 2000. To do this we’ll add two more <code>filter()</code> calls. Copy and run the updated code below.</p>
<pre>data_clean = data %>%
             filter(name == &quot;Page&quot;) %>%
             mutate(name = factor(name)) %>%
             filter(year > 1900) %>%
             filter(year &lt;= 2000)</pre>
<p>The first new <code>filter()</code> call says we only want years greater than 1900 and the second that we only want years less than or equal to 2000, thus giving us our range of 1901 to 2000. We can confirm this by looking at the minimum and maximum years in “data_clean” with the code below.</p>
<pre>min(data_clean$year)
max(data_clean$year)</pre>
<p>It’s okay if the years aren’t exactly 1901 and 2000 (mine are 1909 and 2000), that just means your name didn’t have at least five occurrences in those particular years. Just confirm that you still have some data points and that the minimum and maximum years are within our range.</p>
<p>We’re done with our initial cleaning of the data. Save your script in the “scripts” folder and use a name ending in “_cleaning”, for example mine is called “rcourse_lesson2_cleaning”. Once the file is saved commit the change to Git. My commit message will be “Made cleaning script.”. Finally, push the commit up to Bitbucket.</p>
<h2>Figures Script</h2>
<p>Open a new script in RStudio. You can close the cleaning script or leave it open, we’ll come back to it but you don’t need it right now. This new script is going to be our script for making all of our figures. We’ll start with some new code we haven’t used before. Copy the code before, but don’t necessarily run it.</p>
<pre>## READ IN DATA ####
source(&quot;scripts/rcourse_lesson2_cleaning.R&quot;)</pre>
<p>This <code>source()</code> call tells R to run another script. Specifically to run our cleaning script which is saved in the “scripts” folder. Make sure that the name of your script is correct if it’s not the same as mine. In theory we’ve already run this script since we ran each part of the script separately in the previous section, but to be sure the line of code works look for the symbol of a broom on the “Environment” tab and click it. It should be around the same area as the floppy disk you image you clicked to save the environment in the last lesson. See the screen shot below in case you can’t find it.</p>
<p><a title="" data-rel="lightbox-0" target="_blank" href="http://i2.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot1.png"><img sizes="(max-width: 490px) 100vw, 490px" srcset="http://i0.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot1-490x341.png?resize=456%2C317 490w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot1-226x156.png 226w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot1-768x534.png 768w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot1-1024x712.png 1024w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot1-600x417.png 600w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot1-400x277.png 400w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot1-300x209.png 300w" alt="lesson2_screenshot1" class="wp-image-3960" src="http://i0.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot1-490x341.png?resize=456%2C317" data-recalc-dims="1"></a></p>
<p>After clicking the broom image your “Environment” should now be empty, whereas before it listed both “data” and “data_clean” as shown in the screen shot above. Now run the line of code beginning with <code>source()</code> above. You should see all of your variables reappear as R runs your cleaning script. Having two separate scripts that are connected can be useful to avoid having a single very long script. Also, if someone is interested in your figures script but not your cleaning script you can send them both, but tell them they only need to look at the figures script.</p>
<p>Now we can load in any packages we didn’t pre-load in our cleaning script. Right now it’s only <code>ggplot2</code>. Copy and run the code below.</p>
<pre>## LOAD PACKAGES ####
library(ggplot2)</pre>
<p>Even though our data is cleaned we may still want to change it to a bit for our figures. There’s nothing yet, but it’s still good to make a separate data frame for the figures just in case. Copy and run the code below.</p>
<pre>## ORGANIZE DATA ####
data_figs = data_clean</pre>
<p>Now we can start with our figures, but our first figure won’t be looking at either of our questions. Instead we first have to check that our dependent variable (proportion of the population) has a normal distribution, as that is an assumption of linear regression. To do that we’ll start by making a histogram of our data. Copy and run the code below.</p>
<pre>## MAKE FIGURES ####
# Histogram of dependent variable (proportion of 'Page's)
name.plot = ggplot(data_figs, aes(x = prop)) +
            geom_histogram()

# pdf(&quot;figures/name.pdf&quot;)
name.plot
# dev.off()</pre>
<p>You should now see a histogram in one of your panes. Mine is presented below. To save the figure to a PDF simple delete the <code>#</code> comments before <code>pdf(&quot;figures/name.pdf&quot;)</code> and <code>dev.off()</code> and rerun those three lines of code. One thing you may notice about this code is how it differs from the boxplots we made in the previous lesson. Whereas in the previous lesson we set both <code>x</code> and <code>y</code> in <code>aes()</code>, for this figure we only set <code>x</code>, since a histogram is only plotting one variable, not two. In this case our <code>x</code> is set to “prop”, which is the proportion of the US population that year given your specific name at birth, separated by sex. Also, you may get an error message about setting bin size, that is simply because you did not tell R how large of bins to make for the histogram. Lacking a specific setting R will pick what it thinks is the best, but you can change this in your code if you want.</p>
<p><a title="" data-rel="lightbox-1" target="_blank" href="http://i0.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot2.jpg"><img sizes="(max-width: 490px) 100vw, 490px" srcset="http://i1.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot2-490x490.jpg?resize=456%2C456 490w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot2-768x768.jpg 768w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot2-1024x1024.jpg 1024w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot2-600x600.jpg 600w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot2-300x300.jpg 300w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot2-144x144.jpg 144w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot2.jpg 1050w" alt="lesson2_screenshot2" class="wp-image-3961" src="http://i1.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot2-490x490.jpg?resize=456%2C456" data-recalc-dims="1"></a></p>
<p>As you can see my distribution is very non-normal, so it can’t be used for a linear regression. Yours may look fine, or yours may have a different distribution entirely. A common way to make data more normal is to take a log transform. To do this in R is very simple, you just use the call <code>log()</code> and put what ever you want the log of inside of your parentheses. It’s important to note though that while most people think of log base 10 as the default, in R the default is log base e. To get log base 10 the call is <code>log10()</code>. We’ll run both of these to see how they are different.</p>
<p>To get our log transforms of our data, go back to your cleaning script. Copy and run the code below.</p>
<pre>data_clean = data %>%
            filter(name == &quot;Page&quot;) %>%
            mutate(name = factor(name)) %>%
            filter(year > 1900) %>%
            filter(year &lt;= 2000) %>%
            mutate(prop_loge = log(prop)) %>%
            mutate(prop_log10 = log10(prop))</pre>
<p>We’ve added two lines of code here. Recall that <code>mutate()</code> is used to make new columns in addition to modifying existing ones. With these lines we make two new columns in our data frame: 1) “prop_loge”, and 2) “prop_log10”. The first column takes our “prop” column and does a log based e transform using the <code>log()</code> call. The second column takes our “prop” column and a log based 10 transform using the <code>log10()</code> call. Save the script.</p>
<p>To make our figures you can either rerun the block of code we just updated for “data_clean”, or you can rerun the line of code beginning with <code>source()</code> in our figures script. Either way is fine. Once you are done be sure to rerun the line of code to make the “data_figs” data frame.</p>
<p>Now that we have our log transforms we can look at the distribution of our data again. We’ll make two new figures, one for each of our transforms. For the log base e transform copy and run the code below:</p>
<pre># Histogram of dependent variable (number of 'Page's) - e based log transform
name_loge.plot = ggplot(data_figs, aes(x = prop_loge)) +
                 geom_histogram()
# pdf(&quot;figures/name_loge.pdf&quot;)
name_loge.plot
# dev.off()</pre>
<p>For the log base 10 transform copy and run the code below:</p>
<pre># Histogram of dependent variable (number of 'Page's) - 10 based log transform
name_log10.plot = ggplot(data_figs, aes(x = prop_log10)) +
                  geom_histogram()

# pdf(&quot;figures/name_log10.pdf&quot;)
name_log10.plot
# dev.off()</pre>
<p>My two figures are presented below.<br>
<a title="" data-rel="lightbox-2" target="_blank" href="http://i1.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot3.jpg"><img sizes="(max-width: 490px) 100vw, 490px" srcset="http://i0.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot3-490x490.jpg?resize=456%2C456 490w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot3-768x768.jpg 768w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot3-1024x1024.jpg 1024w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot3-600x600.jpg 600w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot3-300x300.jpg 300w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot3-144x144.jpg 144w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot3.jpg 1050w" alt="lesson2_screenshot3" class="wp-image-3962" src="http://i0.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot3-490x490.jpg?resize=456%2C456" data-recalc-dims="1"></a></p>
<p><a title="" data-rel="lightbox-3" target="_blank" href="http://i0.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot4.jpg"><img sizes="(max-width: 490px) 100vw, 490px" srcset="http://i0.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot4-490x490.jpg?resize=456%2C456 490w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot4-768x768.jpg 768w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot4-1024x1024.jpg 1024w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot4-600x600.jpg 600w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot4-300x300.jpg 300w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot4-144x144.jpg 144w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot4.jpg 1050w" alt="lesson2_screenshot4" class="wp-image-3963" src="http://i0.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot4-490x490.jpg?resize=456%2C456" data-recalc-dims="1"></a></p>
<p>As you can tell the two figures look identical. The only difference is the x-axis range, which is a result of the base of the log transform. So, what you use as a base is not important for how it transforms the data, but it is important to know in case anyone wants to back transform your data into the original values. We’ll be continuing with the log 10 transform since that’s what people are more used to, but be sure to always specify the type of transform you used. We also see from these figures that the distribution is more or less normal, so we’re going to continue with our transformed values for our analyses. If your data is still not normal that means you probably should not being doing a linear regression with your data. Continue along for the sake of the exercise, but know that if you are analyzing real data you should probably look for another statistical test to use.</p>
<p>Let’s now make the figure for our first question about how the popularity of my name, “Page”, changes over time. Once again we have two variables we’re plotting, year and proportion log transformed, so we have two value for <code>aes()</code>. To make the plot a scatterplot we’ll use the <code>geom_point()</code> call. Finally, to add a regression line we use the call <code>geom_smooth()</code> and set <code>method = &quot;lm&quot;</code> to make a linear regression line. Copy the code below to make the plot for your name.</p>
<pre># Proportion of 'Page's by year (continuous predictor)
year.plot = ggplot(data_figs, aes(x = year, y = prop_log10)) +
            geom_point() +
            geom_smooth(method=&quot;lm&quot;)

# pdf(&quot;figures/year.pdf&quot;)
year.plot
# dev.off()</pre>
<p>As you can see in the figure below, there is not much of an effect of time on the proportion of the population with the name “Page”. There may be a slightly increase over time but it is very marginal.</p>
<p><a title="" data-rel="lightbox-4" target="_blank" href="http://i1.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_plotyear.jpg"><img sizes="(max-width: 490px) 100vw, 490px" srcset="http://i0.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_plotyear-490x490.jpg?resize=456%2C456 490w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_plotyear-768x768.jpg 768w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_plotyear-1024x1024.jpg 1024w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_plotyear-600x600.jpg 600w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_plotyear-300x300.jpg 300w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_plotyear-144x144.jpg 144w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_plotyear.jpg 1050w" alt="lesson2_plotyear" class="wp-image-3968" src="http://i0.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_plotyear-490x490.jpg?resize=456%2C456" data-recalc-dims="1"></a></p>
<p>The next figure we’ll make is for our second question, seeing if there is a difference by sex in terms of popularity. For this figure we’ll once again make a boxplot. See and run the code below.</p>
<pre># Proportion of 'Page's by sex (categorical predictor)
sex.plot = ggplot(data_figs, aes(x = sex, y = prop_log10)) +
           geom_boxplot()

# pdf(&quot;figures/sex.pdf&quot;)
sex.plot
# dev.off()</pre>
<p>You may notice that the labels are just “F” and “M” in the plot. It’s useful to have the shorthand labels when analyzing the data, but for my figures I want more explicit labels. To do that I’m going to update the code for my “data_figs” data frame at the top of the script. See the updated code below.</p>
<pre>data_figs = data_clean %>%
            mutate(sex = factor(sex, levels=c(&quot;F&quot;, &quot;M&quot;), labels=c(&quot;female&quot;, &quot;male&quot;)))</pre>
<p>Once again we’re using a <code>mutate()</code> call to update an existing column, “sex”. We’re also using the <code>factor()</code> call again, but this time we are changing the labels. With this line of code we tell R to set “F” to “female” and “M” to “male”. If you rerun this chunk of code and then rerun the code for the figure you should get the figure below.</p>
<p><a title="" data-rel="lightbox-5" target="_blank" href="http://i0.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_boxplotsex.jpg"><img sizes="(max-width: 490px) 100vw, 490px" srcset="http://i2.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_boxplotsex-490x490.jpg?resize=456%2C456 490w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_boxplotsex-768x768.jpg 768w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_boxplotsex-1024x1024.jpg 1024w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_boxplotsex-600x600.jpg 600w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_boxplotsex-300x300.jpg 300w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_boxplotsex-144x144.jpg 144w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_boxplotsex.jpg 1050w" alt="lesson2_boxplotsex" class="wp-image-3964" src="http://i2.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_boxplotsex-490x490.jpg?resize=456%2C456" data-recalc-dims="1"></a></p>
<p>This is one of the reasons why it’s nice to have separate data frames for different scripts. Later on it will be easier to have short label names, but specifically for my figures I want longer, more expressive label names.</p>
<p>We’ve successfully made a figure for each of our analyses, one of which was a new type of figure for us, a scatterplot. As for Lesson 1, for code on how to “prettify” the figure see the full code linked to at the top of this lesson.</p>
<p>We’re done with making our figures. Save your script in the “scripts” folder and use a name ending in “_figures”, for example mine is called “rcourse_lesson2_figures”. Once the file is saved commit the change to Git. My commit message will be “Made figures script. Update cleaning script.” since I also added the log transform columns to my cleaning script. Finally, push the commit up to Bitbucket.</p>
<h2>Statistics Script</h2>
<p>With our figures in place we can finally make our statistics script. Open a new script and on the first line write the following, same as for our figures script.</p>
<pre>## READ IN DATA ####
source(&quot;scripts/rcourse_lesson2_cleaning.R&quot;)</pre>
<p>Next add a place to load packages, such as shown below.</p>
<pre>## LOAD PACKAGES #####
# [none currently needed]</pre>
<p>Note, for this script we’re actually not going to load any packages. You may wonder then, why bother making a section for it? Well for one it’s good practice to do this all the time, even when you don’t need it. Two, you may later decide to add a package and it’s good to already have a place for it in your script.</p>
<p>Also as before we’re going to make a new data frame for our statistics data.</p>
<pre>## ORGANIZE DATA ####
data_stats = data_clean</pre>
<p>Be sure to run all of these lines of code before beginning with the modeling. Our first model looks at the effect of year on popularity of your name. Copy the code below to build your model.</p>
<pre>## BUILD MODEL - PROPORTION OF 'PAGE'S BY YEAR (CONTINUOUS PREDICTOR) ####
year.lm = lm(prop_log10 ~ year, data = data_stats)</pre>
<p>First I’m going to save my model to the name “year.lm”. Note, as for the use of “.plot” for figures, the use of “.lm” here is not required, it’s simply a convention I use to know what my objects are, in this case a linear model. The call itself (<code>prop_log10 ~ year</code>) is explained in more detail in the video above, and then finally we tell R what data frame to look at to find our variables.</p>
<p>With our model saved we use the <code>summary()</code> call to look at the actual results of our model. See the code below, once again I’ve opted to save this summary so it can be called on later.</p>
<pre>year.lm_sum = summary(year.lm)
year.lm_sum</pre>
<p>The summary of the model is provided below. In this particular case the exact numbers of the intercept and the estimate for “year” (the slope) are not very informative, since they are in log transformed values. Importantly for us though we see that there is no effect of year, as our t-value is 1.48 and our p-value is 0.14. So, we can say that the popularity of the name “Page” has not significantly changed over time.</p>
<p><a title="" data-rel="lightbox-6" target="_blank" href="http://i2.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot5.png"><img sizes="(max-width: 490px) 100vw, 490px" srcset="http://i1.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot5-490x354.png?resize=456%2C329 490w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot5-768x555.png 768w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot5-600x434.png 600w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot5-300x217.png 300w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot5.png 924w" alt="lesson2_screenshot5" class="wp-image-3965" src="http://i1.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot5-490x354.png?resize=456%2C329" data-recalc-dims="1"></a></p>
<p>We can also look at the residuals of our model with the <code>resid()</code> call. I’ve saved them to a new object and then called a <code>head()</code> to look at the first few data points. I haven’t included them here, but you should see them in your Console.</p>
<pre>year.lm_resid = resid(year.lm)
head(year.lm_resid)</pre>
<p>We can now conduct our second analysis, looking at the categorical variable of sex. The model is almost identical to our model for year, except that we replace “year” with “sex” as shown in the code below.</p>
<pre>## BUILD MODEL - PROPORTION OF 'PAGE'S BY SEX (CATEGORICAL PREDICTOR) ####
sex.lm = lm(prop_log10 ~ sex, data = data_stats)

sex.lm_sum = summary(sex.lm)
sex.lm_sum</pre>
<p>Below is the summary of the model. Here we do get a significant effect of sex (t = -5.68, p &lt; 0.001). To understand the direction of the effect we look at the line that begins with “sexM”. R by default codes variables alphabetically, so our default level is “F” for female. We can also see this by the fact that “sexM” lets you known that “M” is the non-default level. If “F” were the non-default level it would appear as “sexF”. Again, the actual value of our estimate is not very useful due to our log transform, but the direction of it is. Our estimate is -0.23. The fact that it is negative let’s us know that “Page” is significantly <em>less </em>common of a name (lower proportion of the population) for males than females.</p>
<p><a title="" data-rel="lightbox-7" target="_blank" href="http://i1.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot6.png"><img sizes="(max-width: 490px) 100vw, 490px" srcset="http://i2.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot6-490x344.png?resize=456%2C320 490w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot6-768x539.png 768w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot6-600x421.png 600w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot6-300x211.png 300w, http://datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot6.png 926w" alt="lesson2_screenshot6" class="wp-image-3966" src="http://i2.wp.com/datascienceplus.com/wp-content/uploads/2016/05/lesson2_screenshot6-490x344.png?resize=456%2C320" data-recalc-dims="1"></a></p>
<p>Finally, we can look at the residuals of our model and the first few values.</p>
<pre>sex.lm_resid = resid(sex.lm)
head(sex.lm_resid)</pre>
<p>You’ve now successfully run two linear regressions in R, one with a continuous predictor and one with a categorical predictor. Save your script in the “scripts” folder and use a name ending in “_statistics”, for example mine is called “rcourse_lesson2_statistics”. Once the file is saved commit the change to Git. My commit message will be “Made statistics script.”. Finally, push the commit up to Bitbucket.</p>
<h2>Write-up</h2>
<p>As always, we’ll end the lesson by writing a summary of our results. First save your current working environment to a file such as “rcourse_lesson2_environment” to your “write_up” folder. If you forgot how to do this go back to <a target="_blank" href="http://datascienceplus.com/r-for-publication-by-page-piccinini-lesson-1-r-basics/">Lesson 1</a>. Open a new R Markdown document and follow the steps to get a new script. As before delete everything below the chuck of script enclosed in the two sets of <code>---</code>. Then on the first line use the following code to load our environment.</p>
<pre>```{r, echo=FALSE}
load(&quot;rcourse_lesson2_environment.RData&quot;)
```</pre>
<p>The <code>echo=FALSE</code> setting is new. This simple tells R not to print out the code we ran. That way you can load your environment without necessarily printing that in your write-up. Next we can make our sections for the write-up. I’m going to have three: 1) Introduction, 2) Results, 3) Conclusion, and within Results I have two sections: 1) Prevalence by Year, and 2) Prevalence by Sex. See below for structure.</p>
<pre># Introduction

# Results

## Prevalence by Year

## Prevalence by Sex

# Conclusion</pre>
<p>In each of my sections I can write a little bit for any future readers. For example below is my Introduction.</p>
<pre># Introduction
I looked at how common my name, &quot;Page&quot;, is in the United States population both by year and sex.</pre>
<p>Turning to the results section. I can include both my figure and my model results. For example, below is the code for my first subsection of Results, Prevalence by Year.</p>
<pre>## Prevalence by Year
Below is a plot for how the proportion of people with the name &quot;Page&quot; (log base 10 transformed) has changed over time. Overall the trend is pretty flat, with maybe a slight increase over time.
```{r, fig.align='center'}
year.plot
```
To test if there is a significant effect of year a linear model was built. Proportion of the population log base 10 transformed was the dependent variable and year the independent variable. As shown below, year was not significant, although the coefficients do show a positive slope.
```{r}
year.lm
```</pre>
<p>Remember, anything between the three <code>` ` `</code> is read as R code.</p>
<p>Go ahead and fill out the rest of the document as is appropriate for your results, or look at the full version of my write-up with the link provided at the top of the lesson. When you are ready, save the script to your “write_up” folder and compile the HTML or PDF file. Once your write-up is made, commit the change to Git. My commit message will be “Made write-up.”. Finally, push the commit up to Bitbucket. If you are done with the lesson you can go to your Projects menu and click “Close Project”.</p>
<p>Congrats! You’re all done with the lesson!</p>
<h2>Conclusion and Next Steps</h2>
<p>By now you have learned how to run a new statistic in R. We also made a new kind of figure in <code>ggplot2</code> (a scatterplot) and used another <code>dplyr</code> verb (<code>mutate()</code>). If you go back to the video you’ll see some “food for thought for a future lesson”. Specifically, what happens when two variables interact. We’ll go over how to deal with this soon, but first we have to discuss logistic regression, that will be our next lesson.</p>
<ul>
<li><a target="_blank" href="https://www.youtube.com/watch?v=UrMDPJkmd9E">Lesson 2: Linear Regression</a></li>
</ul>
<p><strong>
<p>Related Post</p>
<p>
<ol>
<li><a title="Permanent Link toHow to detect heteroscedasticity and rectify it?" target="_blank" rel="bookmark" href="http://datascienceplus.com/how-to-detect-heteroscedasticity-and-rectify-it/">How to detect heteroscedasticity and rectify it?</a></li>
<li><a title="Permanent Link toUsing Linear Regression to Predict Energy Output of a Power Plant" target="_blank" rel="bookmark" href="http://datascienceplus.com/linear-regression-predict-energy-output-power-plant/">Using Linear Regression to Predict Energy Output of a Power Plant</a></li>
<li><a title="Permanent Link toHow to Perform a Logistic Regression in R" target="_blank" rel="bookmark" href="http://datascienceplus.com/perform-logistic-regression-in-r/">How to Perform a Logistic Regression in R</a></li>
<li><a title="Permanent Link toFitting Polynomial Regression in R" target="_blank" rel="bookmark" href="http://datascienceplus.com/fitting-polynomial-regression-r/">Fitting Polynomial Regression in R</a></li>
<li><a title="Permanent Link toBivariate Linear Regression" target="_blank" rel="bookmark" href="http://datascienceplus.com/bivariate-linear-regression/">Bivariate Linear Regression</a></li>
</ol></strong>
<div>
<a target="_blank" href="http://feeds.feedburner.com/~ff/datascienceplus?a=ujshmEUYYvE:mHPWmmy2_gc:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/datascienceplus?i=ujshmEUYYvE:mHPWmmy2_gc:D7DqB2pKExk" border="0"></a> <a target="_blank" href="http://feeds.feedburner.com/~ff/datascienceplus?a=ujshmEUYYvE:mHPWmmy2_gc:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/datascienceplus?d=qj6IDK7rITs" border="0"></a> <a target="_blank" href="http://feeds.feedburner.com/~ff/datascienceplus?a=ujshmEUYYvE:mHPWmmy2_gc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/datascienceplus?d=yIl2AUoC8zA" border="0"></a>
</div>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="http://www.r-bloggers.com/r-for-publication-by-page-piccinini-lesson-2-linear-regression/"></div></div><div><a data-url="http://www.r-bloggers.com/r-for-publication-by-page-piccinini-lesson-2-linear-regression/" data-counturl="http://www.r-bloggers.com/r-for-publication-by-page-piccinini-lesson-2-linear-regression/" data-count="vertical" data-text="R for Publication by Page Piccinini: Lesson 2 – Linear Regression" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://datascienceplus.com/r-for-publication-by-page-piccinini-lesson-2-linear-regression/"> DataScience+</a></strong>.</div>
<hr>
<a rel="nofollow" href="http://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="http://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="http://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="http://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="http://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="http://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="http://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="http://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="http://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="http://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="http://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="http://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="http://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="http://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="http://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="http://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="http://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="http://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="http://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/djxEsc3SS7o"></a></div></blockquote></blockquote>