In slides, a command (we’ll also call them code or a code chunk) will look like this
head(mtcars)
mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
And then directly after it, will be the output of the code.
These slides were made in R using knitr
and R Markdown
(covered later today when we discuss reproducible research)
A few reminders: * You can create variables from within the R environment and from files on your computer * Use “<-” to assign values to a variable name * Variable names are case-sensitive, i.e. X and x are different
x <- 2 x
[1] 2
x * 4
[1] 8
x + 2
[1] 4
For any function, you can write ?FUNCTION_NAME
, or help("FUNCTION_NAME")
to look at the help file:
?dir help("dir")
Not all packages are available by default.
install.packages("tidyverse") library(tidyverse)
Commenting in code is super important. You should be able to go back to your code years after writing it and figure out exactly what the script is doing. Commenting helps you do this. Also handy for notes!
Let’s make an R Project so we can stay organized in the next steps.
Click the new R Project button at the top left of RStudio:
In the New Project Wizard, click “New Directory”:
Click “New Project”:
Type in a name for your new folder.
Store it somewhere easy to find, such as your Desktop:
You now have a new R Project folder on your Desktop!
Make sure you add any scripts or data files to this folder as we go through today’s lesson. This will make sure R is able to “find” your files.
Youth Tobacco Survey (YTS) dataset:
“The YTS was developed to provide states with comprehensive data on both middle school and high school students regarding tobacco use, exposure to environmental tobacco smoke, smoking cessation, school curriculum, minors’ ability to purchase or otherwise obtain tobacco products, knowledge and attitudes about tobacco, and familiarity with pro-tobacco and anti-tobacco media messages.”
Dataset is located at https://sisbid.github.io/Data-Wrangling/data/Youth_Tobacco_Survey_YTS_Data.csv
Download data by clicking the above link
>
File>
Import Dataset>
From Text (readr
)>
paste the url (https://sisbid.github.io/Data-Wrangling/data/Youth_Tobacco_Survey_YTS_Data.csv)>
click “Update” and “Import”Youth_Tobacco_Survey_YTS_Data
in your environment pane (top right). The table button opens the data for you to view.