huge community and package ecosystem (20,000+ packages on CRAN)
Why R: reproducibility and replicability
Term
Meaning
Reproducibility
Same data, same methods
Replicability
New data, same methods
A script records every step, which makes your work reproducible
Most scientists report failing to reproduce others’ results, and many
their own. Survey of 1,576 researchers (Baker, 2016, Nature).
Motivation 🤔
Stand on the shoulders of giants: others can only
build on your work if they can see what you did
Efficiency: automate repetitive tasks, get to the
important task of thinking
Scale: work with datasets far too large for a
spreadsheet
Your future self: six months from now, you’ll need
to know what you did, too
R vs. RStudio
R is the engine: the language that does the
computing
RStudio is the dashboard: an interface that makes R
easier to drive (an integrated development environment or
IDE)
Today’s Goals
By the end of this session, you should be able to:
Find your way around RStudio
Install and load packages
Run code and use functions
Create and name variables
Recognize R’s main data types and data structures
Know where to look for help
RStudio
Installing packages
# install.packages("dplyr") # This call installs a package # library(dplyr) # This loads a package# devtools packages# install.packages("devtools")# install_github("username/repositoryname")
Simple Math
2+2# add
## [1] 4
3-2# subtract
## [1] 1
3*3# multiply
## [1] 9
4/2# division
## [1] 2
sqrt(9) # square root
## [1] 3
Functions
# c() is a common function for concatenating things togetherc(1:10)
## [1] 1 2 3 4 5 6 7 8 9 10
Variables
Creating variables
# You can then recall the values (object) associated with your variable...my_variable <-c(1:10)myAlphabet <- letters[1:5]myNumbers <-c(1:5)#And plug it into functions, ie, do computations on it...my_variable
## [1] 1 2 3 4 5 6 7 8 9 10
my_variable *2
## [1] 2 4 6 8 10 12 14 16 18 20
Naming variables
# camel casemyNumber <-"Hello"# bad namingmyNumber <-10# good naming# skeleton casemy_number <-10
Data types
data (and the variables that we use to store them) come in different
shapes and sizes
think of a variable as a box and the data are the things
you want to put in, not all boxes fit all types of stuff (data)
note: the function typeof(), will tell
you what data type you have…
Boolean (Logical Data)
boolean data are generally referred to as
logical
myBool <-TRUE# this is camel casetypeof(myBool)
## [1] "logical"
Numeric (Double)
in Rnumeric data are subdivided into
double and integer
myDouble <-10.5typeof(myDouble)
## [1] "double"
Numeric (Integer)
myInteger <-10Ltypeof(myInteger)
## [1] "integer"
Characters
character data always needs to be wrapped in single or
double quotations.
myChar <-"a"# Note that R does not distinguish between '' and "" but the use has to matchtypeof(myChar)