Statistics + Computing
There are many, many statistical packages, see http://en.wikipedia.org/wiki/List_of_statistical_packages
In this class, we will discuss some basic computer science concepts, but we will emphasize skills for utilizing computers to aid in data analysis.
Advances in computation have enabled advances at every step of the data analysis pipeline:
## [1] 9
## [1] 3
## [1] 18
## [1] 2
## [1] 35
## [1] 16807
## [1] 1.4
## [1] 2
## [1] 4
## [1] 120
## [1] 24
## [1] 70
## [1] 4
## [1] 10
## [1] 1.414214
## [1] 70
## [1] 4
## [1] TRUE
## [1] FALSE
## [1] FALSE
## [1] TRUE
## [1] TRUE
## [1] FALSE
## [1] TRUE
## [1] FALSE
## [1] TRUE
## [1] TRUE
## [1] FALSE
## [1] 7
## [1] 10
## [1] TRUE
## [1] "7"
## [1] 10
We can give names to data objects; these give us variables. Some variables are built-in:
## [1] 3.141593
Variables can be arguments to functions or operators, just like constants:
## [1] 31.41593
## [1] -1
We create variables with the assignment operator,
<- or =
## [1] 3.142857
## [1] 31.42857
## [1] 7 8 10 45
## [1] TRUE
c() function returns a vector containing all its
arguments in specified order1:5 is shorthand for c(1,2,3,4,5), and so
onx[1] would be the first element, x[4] the
fourth element, and x[-4] is a vector containing all
but the fourth element.Arithmetic operator apply to vectors in a “component wise” fashion
## [1] 0 0 0 0
## [1] -49 -64 -100 -2025
## [1] 4
## [1] 4
## [1] 0 0 3 37
## [1] 7.000000 1.000000 0.100000 6.708204
## [1] 14 16 20 90
## [1] FALSE FALSE TRUE TRUE
Logical operators also work elementwise:
## [1] FALSE FALSE TRUE FALSE
Let’s try making an RMarkdown file:
Homework_1.Rmd.Files tab. What do you notice?
Click Open in Browser to view the full HTMLtitle to “Homework 1”author to your name in quotesdate to the due date in quotesBold - bold/strong emphasis
italic - italic/normal emphasis
Header - # Header
Subheader - ## Subheader
Subsubheader - ### Subsubheader
Links - URLs are trivial
Picture - Picture
As you saw before, we can run and execute R code within R Markdown. To do so encase your code as follows.
You can click the green triangle in the corner to evaluate that code chunk to preview the results without compiling the entire document.
Parameters go into the opening brackets {r} and are
separated by commas. Here are some you might find useful (checkout the
guide links above for more):
echo=FALSE: Hide R code but keep results
eval=FALSE: Do not execute the R code
include=FALSE: Hides all output (useful to load
packages at the beginning of your document)
cache=TRUE: Stores the results of the chunk, and
only re-runs if the chunk is changed. Useful for files that take a while
to compile
fig.height=5, fig.width=5: modify the dimensions of
any plots that are generated in the chunk (units are in inches)
To handle equations, see R Markdown Equations
Helpful Links
## speed dist
## Min. : 4.0 Min. : 2.00
## 1st Qu.:12.0 1st Qu.: 26.00
## Median :15.0 Median : 36.00
## Mean :15.4 Mean : 42.98
## 3rd Qu.:19.0 3rd Qu.: 56.00
## Max. :25.0 Max. :120.00
c()## [1] 16 3 0 7 -2
:## [1] 1 2 3 4 5
rep() and seq()## [1] 1 6 11 16
## [1] 1 1 1 2 2 2
## [1] 1 2 1 2 1 2
[index] after the vector
name## [1] 3
## [1] 1 2 3 5
## [1] 1 2 3 4 5
## [1] -5 -4 -3 -2 -1
## [1] -4 -2 0 2 4
## [1] -5 -8 -9 -8 -5
## [1] 1 2 3 4 5
## [1] 2 4 6 8 10
## Warning in c(1, -1) * x: longer object length is not a multiple of shorter
## object length
## [1] 1 -2 3 -4 5
## Warning in c(1, -1) + x: longer object length is not a multiple of shorter
## object length
## [1] 2 1 4 3 6
## [1] FALSE FALSE TRUE TRUE TRUE
## [1] TRUE TRUE TRUE FALSE FALSE
## [1] FALSE FALSE TRUE FALSE FALSE
## [1] TRUE FALSE FALSE TRUE TRUE
## [1] FALSE FALSE TRUE TRUE TRUE
## [1] TRUE TRUE TRUE FALSE FALSE
## [1] FALSE FALSE TRUE FALSE FALSE
## [1] TRUE FALSE FALSE TRUE TRUE
In code, entries that are TRUE or FALSE
are called booleans.
These are incredibly important, because they can be used to give your computer conditions. What will the following code do?
## [1] 1 2 3 3 3
## [1] 1 2 3 3 3
TRUE is
encoded as 1 and FALSE is encoded as
0.## [1] 1 2 3 4 5
## [1] 3
## [1] 0.6
What is this last quantity telling us?
By taking the mean, we are looking at the
proportion of our vector that is
TRUE!
names(). This can be useful to label our data. Note that
arithmetic doesn’t change the names of our elements.## a b c
## 1 2 3
## a b c
## 2 3 4
We can then access the names as their own vector by calling
names() again.
## [1] "a" "b" "c"
max(), min(), mean(),
median(), sum(), sd(),
var()length() returns the number of elements in the
vectorhead() and tail() return the beginning and
end vectorssort() will sortsummary() returns a 5-number summaryany() and all() to check conditions on
Boolean vectorshist() will return a crude histogram (we’ll learn how
to make this nicer later)If you are unclear about what any of them do, use ?
before the function name to read the documentation. You should get in
the habit of checking function documentation a lot!
Matrices are two-dimensional extension of vectors, they have rows and columns
We can create a matrix using the function
matrix()
A matrix object is a rectangular \(n\) × \(m\) array of elements of same type: numerical, character, etc.
n is the number of rows, m is the number of columns.
Typically rows represent subjects, and columns represent different variables measured for each subject.
The rectangular data structure ensures same number of measurements per subject.
Having more than one variable per subject allows us to examine correlations between various measurements.
We could also view such data as a collection of equal length variable vectors, stacked next to each other.
## [,1] [,2] [,3] [,4]
## [1,] 1 4 7 10
## [2,] 2 5 8 11
## [3,] 3 6 9 12
## [,1] [,2] [,3] [,4]
## [1,] "a" "b" "c" "d"
## [2,] "e" "f" "g" "h"
## [3,] "i" "j" "k" "l"
# Only nrow or ncol need to be specified
my_matrix <- matrix(1:12, nrow = 3, ncol = 4, byrow = TRUE)
my_matrix## [,1] [,2] [,3] [,4]
## [1,] 1 2 3 4
## [2,] 5 6 7 8
## [3,] 9 10 11 12
## [,1] [,2] [,3] [,4]
## [1,] 1 4 7 10
## [2,] 2 5 8 11
## [3,] 3 6 9 12
cbind()) and row binding (rbind())
vectors## [,1] [,2] [,3] [,4]
## [1,] 1 4 7 10
## [2,] 2 5 8 11
## [3,] 3 6 9 12
## [,1] [,2] [,3] [,4]
## [1,] "a" "b" "c" "d"
## [2,] "e" "f" "g" "h"
## [3,] "i" "j" "k" "l"
## NULL
## [,1] [,2] [,3] [,4]
## row1 1 4 7 10
## row2 2 5 8 11
## row3 3 6 9 12
## col1 col2 col3 col4
## row1 1 4 7 10
## row2 2 5 8 11
## row3 3 6 9 12
## col1 col2 col3 col4
## row1 1 4 7 10
## row2 2 5 8 11
## row3 3 6 9 12
## [1] 3 4
## col3 col4
## row1 7 10
## row2 8 11
## [1] 11
Matrices are added by adding corresponding elements. Matrices must have same dimension (columns and rows).
Same for -, *, / .
## [,1] [,2] [,3] [,4]
## [1,] 12 9 6 3
## [2,] 11 8 5 2
## [3,] 10 7 4 1
## col1 col2 col3 col4
## row1 13 13 13 13
## row2 13 13 13 13
## row3 13 13 13 13
## col1 col2 col3 col4
## row1 1 4 7 10
## row2 2 5 8 11
## row3 3 6 9 12
## col1 col2 col3 col4
## row1 2 5 8 11
## row2 4 7 10 13
## row3 6 9 12 15
## col1 col2 col3 col4
## row1 1 4 7 10
## row2 2 5 8 11
## row3 3 6 9 12
## col1 col2 col3 col4
## row1 2 8 10 12
## row2 4 6 12 14
## row3 6 8 10 16
## [,1] [,2]
## [1,] 1 3
## [2,] 2 4
## [,1] [,2] [,3]
## [1,] 6 4 2
## [2,] 5 3 1
## [,1] [,2] [,3]
## [1,] 21 13 5
## [2,] 32 20 8
## [,1] [,2]
## [1,] 1 3
## [2,] 2 4
## [1] 2 3
## [,1]
## [1,] 11
## [2,] 16
## [,1] [,2]
## [1,] 1 3
## [2,] 2 4
## [,1] [,2]
## [1,] -2 1.5
## [2,] 1 -0.5
## [1] -2
## [1] 1 4
## [,1] [,2]
## [1,] 1 0
## [2,] 0 1
diag()diag() can also be used to generate diagonal matrices
by supplying a vector.## [,1] [,2] [,3]
## [1,] 1 0 0
## [2,] 0 2 0
## [3,] 0 0 3
## [,1] [,2] [,3]
## [1,] 1 0 0
## [2,] 0 1 0
## [3,] 0 0 1
## [,1] [,2] [,3]
## [1,] 1 4 7
## [2,] 2 5 8
## [3,] 3 6 9
## [,1] [,2] [,3]
## [1,] 1 4 7
## [2,] 2 10 8
## [3,] 3 6 9
## [,1] [,2] [,3]
## [1,] 1 4 7
## [2,] 2 5 8
## [3,] 3 6 9
## [,1] [,2] [,3]
## [1,] 0 0 7
## [2,] 0 5 8
## [3,] 0 6 9
## [,1] [,2] [,3]
## [1,] 1 4 7
## [2,] 2 5 8
## [3,] 3 6 9
## [,1] [,2] [,3]
## [1,] 1 2 3
## [2,] 4 5 6
## [3,] 7 8 9
We can fill in a matrix using indices.
In R, you should always start by initializing an empty matrix of the right size.
## [,1] [,2] [,3]
## [1,] NA NA NA
## [2,] NA NA NA
## [3,] NA NA NA
## [,1] [,2] [,3]
## [1,] NA NA NA
## [2,] 2 4 3
## [3,] NA NA NA
## [,1] [,2] [,3]
## [1,] 7 7 7
## [2,] 2 4 3
## [3,] 7 7 7
## [,1] [,2] [,3]
## [1,] 7 7 7
## [2,] 7 7 7
## [3,] 7 7 7
## [,1] [,2] [,3]
## [1,] 7 7 7
## [2,] 7 7 7
## [3,] 7 7 7
## [,1] [,2] [,3]
## [1,] "1" "2" "3"
## [2,] "a" "b" "c"
## [,1] [,2] [,3]
## [1,] 0.5000000 0.8571429 0.9166667
## [2,] 0.6666667 0.8750000 0.9230769
## [3,] 0.7500000 0.8888889 0.9285714
## [4,] 0.8000000 0.9000000 0.9333333
## [5,] 0.8333333 0.9090909 0.9375000
## [1] 18 21 24 27 30
## [1] 15 40 65
## [1] 6 7 8 9 10
It is easy to go from matrices to tables using RMarkdown. There are several methods (check the cheatsheet link and Google for alternatives). I will present one easy method here, but what you use is up to you!
We need to load the knitr and kableExtra package
## [,1] [,2] [,3]
## [1,] 1 2 3
## [2,] 4 5 6
| 1 | 2 | 3 |
| 4 | 5 | 6 |
What happened with the row and column names?
Packages bundle together code, data, and documentation in an easy to share way.
They come with functions that others have written for you to make your life easier, and greatly improve the power of R!
Packages are the reason we are learning about R in this course.
Packages can range from graphical software, to web scraping tools, statistical models for spatio-temporal data, microbial data analysis tools, and more!
The most popular package repository is the Comprehensive R Archive Network, or CRAN.
CRAN is R’s central software repository, supported by the R Foundation. It contains an archive of the latest and previous versions of the R distribution, documentation, and contributed R packages.
There are almost 18,000 packages currently.
Other popular repositories include Bioconductor and Github.
If a package is available on CRAN, like most packages we will use for
this course, you can install it using
install.packages():
You can also install by clicking Install in the Packages tab through RStudio.
For the most part, after you install a package, it is saved on your computer until you update R, and you will not need to re-install it.
Thus, you should never include a call to
install.packages() in any .R or
.Rmd file!
After a package is installed, you can load it into your current R
session using library():
Note that unlike install.packages(), you do not need to
include the package name in quotes.
Loading a package must be done with each new R session, so you
should put calls to library() in your .R and
.Rmd files.
Usually, I do that in the opening code chunk. If it is a
.Rmd, I set the parameter include = FALSE to
hide the messages and code, because they are usually unnecessary to the
reader of my HTML.
tibbles are a special Tidyverse data frame from the
tibble package.
You can convert data frames to tibbles using
as_tibble(), or you can create them similarly to data
frames using tibble().
The biggest benefit of tibbles is that they display nicer in your R console, automatically truncating output and including variable type to print nicely.
Tidyverse has decided rownames are obsolete, and so they do not
include rownames by default. However, we can include our rownames as a
variable using the parameter rownames in
as_tibble().
library(tibble)
my_data <- data.frame("var1" = 1:3,
"var2" = c("a", "b", "c"),
"var3" = c(TRUE, FALSE, TRUE))
rownames(my_data) <- c("obs1", "obs2", "obs3")
my_data## var1 var2 var3
## obs1 1 a TRUE
## obs2 2 b FALSE
## obs3 3 c TRUE
## # A tibble: 3 × 4
## Observation var1 var2 var3
## <chr> <int> <chr> <lgl>
## 1 obs1 1 a TRUE
## 2 obs2 2 b FALSE
## 3 obs3 3 c TRUE
library(tibble)
my_data <- data.frame("var1" = 1:3,
"var2" = c("a", "b", "c"),
"var3" = c(TRUE, FALSE, TRUE))
rownames(my_data) <- c("obs1", "obs2", "obs3")
my_data## var1 var2 var3
## obs1 1 a TRUE
## obs2 2 b FALSE
## obs3 3 c TRUE
## # A tibble: 3 × 3
## var1 var2 var3
## <int> <chr> <lgl>
## 1 1 a TRUE
## 2 2 b FALSE
## 3 3 c TRUE
There are three rules required for data to be considered tidy
Seems simple, but can sometimes be tricky!
What’s untidy about the following data?
library(kableExtra)
untidy_dat <- data.frame("Hospital" = c("A", "B", "C", "D"),
"Diseased" = c(10, 15, 12, 5),
"Healthy" = c(14, 18, 13, 16))
kable_styling(kable(untidy_dat))| Hospital | Diseased | Healthy |
|---|---|---|
| A | 10 | 14 |
| B | 15 | 18 |
| C | 12 | 13 |
| D | 5 | 16 |
library(kableExtra)
untidy_dat <- data.frame("Hospital" = c("A", "B", "C", "D"),
"Diseased" = c(10, 15, 12, 5),
"Healthy" = c(14, 18, 13, 16))
kable_styling(kable(untidy_dat))| Hospital | Diseased | Healthy |
|---|---|---|
| A | 10 | 14 |
| B | 15 | 18 |
| C | 12 | 13 |
| D | 5 | 16 |
Problem: column headers are values, not variables!
tidy_dat <- data.frame("Hospital" = rep(c("A", "B", "C", "D"), each = 2),
"Status" = rep(c("Diseased", "Healthy"), 4),
"Count" = c(10, 14, 15, 18, 12, 13, 5, 16))
kable_styling(kable(tidy_dat))| Hospital | Status | Count |
|---|---|---|
| A | Diseased | 10 |
| A | Healthy | 14 |
| B | Diseased | 15 |
| B | Healthy | 18 |
| C | Diseased | 12 |
| C | Healthy | 13 |
| D | Diseased | 5 |
| D | Healthy | 16 |
untidy_dat2 <- data.frame("Country" = c("A", "B"),
"Year" = rep(2018, 2),
"m1624" = c(49, 34),
"m2534" = c(55, 33),
"f1624" = c(47, 50),
"f2534" = c(41, 43))
untidy_dat2## Country Year m1624 m2534 f1624 f2534
## 1 A 2018 49 55 47 41
## 2 B 2018 34 33 50 43
untidy_dat2 <- data.frame("Country" = c("A", "B"),
"Year" = rep(2018, 2),
"m1624" = c(49, 34),
"m2534" = c(55, 33),
"f1624" = c(47, 50),
"f2534" = c(41, 43))
kable_styling(kable(untidy_dat2))| Country | Year | m1624 | m2534 | f1624 | f2534 |
|---|---|---|---|---|---|
| A | 2018 | 49 | 55 | 47 | 41 |
| B | 2018 | 34 | 33 | 50 | 43 |
untidy_dat2 <- data.frame("Country" = c("A", "B"),
"Year" = rep(2018, 2),
"m1624" = c(49, 34),
"m2534" = c(55, 33),
"f1624" = c(47, 50),
"f2534" = c(41, 43))
kable_styling(kable(untidy_dat2))| Country | Year | m1624 | m2534 | f1624 | f2534 |
|---|---|---|---|---|---|
| A | 2018 | 49 | 55 | 47 | 41 |
| B | 2018 | 34 | 33 | 50 | 43 |
tidy_dat2 <- data.frame("Country" = rep(c("A", "B"), each = 4),
"Year" = rep(2018, 8),
"Gender" = rep(c("m", "m", "f", "f"), 2),
"Age_Group" = rep(c("16-24", "25-34"), 4),
"Counts" = c(49, 55, 47, 41, 34, 33, 50, 43))
kable_styling(kable(tidy_dat2))| Country | Year | Gender | Age_Group | Counts |
|---|---|---|---|---|
| A | 2018 | m | 16-24 | 49 |
| A | 2018 | m | 25-34 | 55 |
| A | 2018 | f | 16-24 | 47 |
| A | 2018 | f | 25-34 | 41 |
| B | 2018 | m | 16-24 | 34 |
| B | 2018 | m | 25-34 | 33 |
| B | 2018 | f | 16-24 | 50 |
| B | 2018 | f | 25-34 | 43 |
Identify the observations, variables, and values.
Ensure that each observation has its own row. Be careful for individual observations spread over multiple tables/Excel files/etc, or multiple types of observations within a single table (this would result in many empty cells).
Ensure that each variable has its own column. Be careful for variables spread over two columns, multiple variables within a single column, variables as rows.
Ensure that each value has its own cell. Be careful for values as column headers
Easier to read data.
Easier to analyze and plot using standard software (required for
ggplot2).
Easier to understand what the data represents.
Fewer issues with missing values.
## Warning: package 'dplyr' was built under R version 4.2.2
## # A tibble: 18 × 11
## religion `<$10k` $10-2…¹ $20-3…² $30-4…³ $40-5…⁴ $50-7…⁵ $75-1…⁶ $100-…⁷
## <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 Agnostic 27 34 60 81 76 137 122 109
## 2 Atheist 12 27 37 52 35 70 73 59
## 3 Buddhist 27 21 30 34 33 58 62 39
## 4 Catholic 418 617 732 670 638 1116 949 792
## 5 Don’t know/r… 15 14 15 11 10 35 21 17
## 6 Evangelical … 575 869 1064 982 881 1486 949 723
## 7 Hindu 1 9 7 9 11 34 47 48
## 8 Historically… 228 244 236 238 197 223 131 81
## 9 Jehovah's Wi… 20 27 24 24 21 30 15 11
## 10 Jewish 19 19 25 25 30 95 69 87
## 11 Mainline Prot 289 495 619 655 651 1107 939 753
## 12 Mormon 29 40 48 51 56 112 85 49
## 13 Muslim 6 7 9 10 9 23 16 8
## 14 Orthodox 13 17 23 32 32 47 38 42
## 15 Other Christ… 9 7 11 13 13 14 18 14
## 16 Other Faiths 20 33 40 46 49 63 46 40
## 17 Other World … 5 2 3 4 2 7 3 4
## 18 Unaffiliated 217 299 374 365 341 528 407 321
## # … with 2 more variables: `>150k` <dbl>, `Don't know/refused` <dbl>, and
## # abbreviated variable names ¹`$10-20k`, ²`$20-30k`, ³`$30-40k`, ⁴`$40-50k`,
## # ⁵`$50-75k`, ⁶`$75-100k`, ⁷`$100-150k`
## # A tibble: 180 × 3
## religion income frequency
## <chr> <chr> <dbl>
## 1 Agnostic <$10k 27
## 2 Agnostic $10-20k 34
## 3 Agnostic $20-30k 60
## 4 Agnostic $30-40k 81
## 5 Agnostic $40-50k 76
## 6 Agnostic $50-75k 137
## 7 Agnostic $75-100k 122
## 8 Agnostic $100-150k 109
## 9 Agnostic >150k 84
## 10 Agnostic Don't know/refused 96
## # … with 170 more rows
Hadley Wickham is the ultimate resource on tidy data principles. Here is a fantastic reference going through all these principles in more detail and with more examples.
Seeing your working directory
A working directory is the filepath R uses to
save and look for data. You can check for your current working directory
using getwd()
## [1] "C:/Users/princ/OneDrive - University of Connecticut/Desktop/R Markdown/STAT 302 Spring 2023/Introduction to RMarkdown and R Programming"
This location is where R will look by default!
You can change your working directory using setwd().
You can use the shorthand .. to reference a parent
directory relative to where you are now.
## [1] "C:/Users/princ/OneDrive - University of Connecticut/Desktop/R Markdown/STAT 302 Spring 2023/Introduction to RMarkdown and R Programming"
## [1] "C:/Users/princ/OneDrive - University of Connecticut/Desktop/R Markdown/STAT 302 Spring 2023"
Do not change your working directory inside R Markdown files!
By default, R Markdown sets the filepath they are in as the working directory.
Changing this can (will) mess up your analysis, and make your work less reproducible.
You can save single R objects as .rds files using
saveRDS(), multiple R objects as .RData or
.rda files using save(), and your entire
workspace as .RData using save.image().
object1 <- 1:5
object2 <- c("a", "b", "c")
# save only object1
saveRDS(object1, file = "object1_only.rds")
# save object1 and object2
save(object1, object2, file = "both_objects.RData")
# save my entire workspace
save.image(file = "entire_workspace.RData").RData for multiple
objects, and I recommend against using save.image(),
basically ever.You can load .rds files using readRDS() and
.Rdata and .rda files using
load().
The values in quotes are all filepaths, and by default, R will search for these objects in your current working directory.
You can change where R searches for images by adjusting this
filepath. For example, if you save your data in a Data
subfolder within your working directory, you might try
Often, you will read and write files as comma
separated values, or
.csv. You can do this by navigating File > Import
Dataset in the menu bar, but generally I recommend doing it
manually using the readr package. You will need to do so if
loading data is part of your work flow, such as if it is required for an
R Markdown writeup.
library(readr)
# read a .csv file in a "Data" subfolder
read_csv("./Data/file.csv")
# save a .csv file in a "Data" subfolder
write_csv("./Data/data_output.csv")readr can also handle many more types of data! See more
details about readr using the fantastic cheat sheet
available here.Working directories are the default filepaths R uses to save and load files.
When working in a .Rmd, your default filepath is
wherever the .Rmd is stored, and you should leave it
there.
You can change your working directory with
setwd().
You can reference your current working directory using
. and the parent directory of your current working
directory using ..
For larger analysis projects, I recommend using R projects to automatically manage your working directory for you!
Good file organization requires you to keep all your input data, R scripts, output data and results, and figures together. You can do this using Projects.
You can create a project by going to File > New Project. If you want your project in a folder you have already created, select Existing Directory. If you want RStudio to automatically make you a new folder with a project, select New Directory.
Then select Empty Project to create a standard project. This
will create a .Rproj file on your computer.
When working with a project, save and manage your work as usual. When
you close and re-open R, do so by double-clicking on your
.Rproj file! This will automatically open everything
as you left it, except your environment will be fresh, helping with
reproducibility.
Automatically manages your working directory, even if you move the project file.
Remembers your working directory and command history, all the files you were working on are still open.
Helps with reproducibility. You can share R project files and the project will load on other computer exactly as it does on yours.
Helps keep your separate analyses separate. For example, you
won’t need to worry if you defined a variable x in multiple
different analyses.
Easy to integrate with version control such as git (more on this later!)
We will be using a mix of the Tidyverse Style Guide by Hadley Wickham and the Google Style Guide.
Please see the links for details, but I will summarize some main points here and throughout the class as we learn more functionality, such as functions and packages.
You will be graded on following good code style!
Use either underscores (_) or big camel case
(BigCamelCase) to separate words within an object name. Do
not use dots . to separate words in R functions!
Names should be concise, meaningful, and (generally) nouns.
It is very important that object names do not write over common functions!
Note: T and F are R shorthand for
TRUE and FALSE, respectively. In general,
spell them out to be as clear as possible.
==, +, -, <-,
etc.)# Good
height <- (feet * 12) + inches
mean(x, na.rm = 10)
# Bad
height<-feet*12+inches
mean(x, na.rm=10)There are some exceptions we will learn more about later, such as the
power symbol ^. See the Tidyverse Style Guide for more
details!
= or
<-.In R, semi-colons (;) are used to execute pieces of
R code on a single line.
In general, this is bad practice and should be avoided.
Also, you never need to end lines of code with semi-colons!
Strive to limit your code to 80 characters per line. This fits comfortably on a printed page with a reasonably sized font.
If a function call is too long to fit on a single line, use one
line each for the function name, each argument, and the closing
). This makes the code easier to read and to change
later.
# Good
do_something_very_complicated(
something = "that",
requires = many,
arguments = "some of which may be long"
)
# Bad
do_something_very_complicated("that", requires, many, arguments,
"some of which may be long"
)