Chapter 2 R and Calculations
- invent good folder structures for this class
- do not save all of this on desktop / downloads
## [1] 4
## [1] 16
2.1 R is a calculator
- click in a row of code to run it, or highlight chunks of code to run it
- ctrl + enter to run a block
- R does not care about white space
## [1] 5
- We suggest using a readable style for your code
- I suggest STYLR
2.2 Functions
- for most things in R, we will use functions
- functions need inputs (aka arguments), and output something
- outputs can vary drastically, and may include graphs, datasets, animations, etc.
- every function has a name, e.g.
c
- for example, the c function stands for concatenate a vector (a list of things)
- use parenthesis after the function name to list arguments/inputs
## [1] 1 2 3
## [1] 1 2 3
- Code looks best with oxford commas (space after each item)
2.3 Store objects for future use in environment
the vectors above were shown in the console pane, but not saved anywhere
make a vector and and store it as
vector1
object
notice that vector1 was added to the environment pane
Access the object you stored
## [1] 1 2 3
the preferred way to assign a new object is
<-
This avoids the mathematical meaning of
=
2.4 Mean function for averages
google or ChatGPT: “how do I take an average in R?”
Internet is great for finding function names / packages
Use
?
to find help on something, e.g.?mean
Help opens in the help pane
- In a function, the equals sign temporarily assigns inputs to arguments for the purposes of the function
## [1] 2
you do not always need to label arguments
labeling arguments can make code more readable
without labels, R assumes arguments are provided in predetermined order (as shown in help)
Some parameters may have default values as shown in help, e.g.
mean(x, trim = 0, na.rm = FALSE, ...)
story of defaults in a logistic regression function that caused problems in research
trim
would involve removing a proportion of values;na.rm
would involveNA
missing values
## [1] 2
make a vector with missing values
NA
is shown in color, having special meaning
## [1] 5 9 14 NA
- suggests creating descriptive object names
## [1] NA
the answer is not available! We cannot include missing values in math
try using the option to remove missing values
TRUE
is a special word for the logical value “true”
## [1] 9.333333
- aha, now the mean is calculated based on the three known values because we added a parameter to tell the mean function to ignore missing data