R programming tutorial
This R programming tutorial was orignally created by the uWaterloo stats club and MSFA with the purpose of providing the basic information to quickly get students hands dirty using R. Fine the original here
Contents:
R Programming 101 (Beginner Tutorial): Introduction to R Presentation
Presentation in html / Presentation in pdf / Source (r markdown)
R Programming Reference: complilation of useful information and code snippets
Reference in html / Reference in pdf / Source (r markdown)
## Useful Resources:
Learn more R using swirl
R for Statisitical Computing
Download R from CRAN and install
Recommended supplement but not necessary: RStudio from http://www.rstudio.com/products/rstudio/download/
- R Studio: A (very matlab like) IDE for R
Comments
Comments are typed with hashtags ‘#’
No block comments. So sad. =(
Data Types
### Integers & Numerics Examples: 1,2.0,1.1,pi
Inf
can also be used in calculations
Complex Numbers
We can even use complex numbers.
Characters
Example: ‘One’, ‘1’, ‘pi’
Boolian (Logical) Values
Boolian values can take only two values: TRUE
(T
) or FALSE
(F
).
Factors
A factor is a categorical variable that can take on only a finite set of values. i.e. Sex, Faculty in University
Everything is an object, including functions!
Vectors
Most common objects are called vectors.
Examples: vector of numbers
You can also create a range of values using
start:end
Basic Numerical Operations: +, -, *, /, ^
Numerical operations are: +, -, *, /, ^
- These operate elementwise between vectors.
Operator | Description |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
^ | Power |
Note: They don’t have to have the same length. If they don’t then the vector will recycle though the shorter vector. The longer has to be a multiple of the shorter vector.
Logical Operators
- Return a boolan value of
TRUE
orFALSE
Operator | Description |
---|---|
< | Less than |
> | Greater than |
<= | Less than or equal to |
>= | Greater than or equal to |
== | Equal to |
!= | Not equal to |
| | Elementwise Or |
& | Elementwise And |
|| | Or |
&& | And |
Pro Tip: When interacting with number, boolians are converted to an integer: 0, or 1.
Type check
is.(typename)
Example: is.vector
, is.integer
, is.numeric
, is.data.frame
, is.matrix
- Not sure which type? Use
typeof()
!
Assignment Operator
Assignment can come in 3 forms:
var_name <- evaluation
var_name = evaluation
evaluation -> var_name
Be careful: <- is not the same as < -
Concatenating Vectors
They are different vectors!
To concatenate two vectors, use c(vector.1, vector.2)
Notice that when combined with characters, numerics are changed into characters automatically. So b23 == b21
.
Dot Product
To use dot product of two vectors (instead of elementwise) use %*%
##Exercise
1. What are the datatypes available in R?
2. What datatype would the vector c(1,2,"three")
be?
3. What is the vector c(3,4,5,6)
to the power of 4?
4. What elements of c(3,4,5,6)
greater than 4?
##Answer 1. What are the datatypes available in R? - Numeric - Integer - Complex - Character - Boolian - Factor
- What datatype would the vector
c(1,2,"three")
be?- Character
- What is the vector
c(3,4,5,6)
to the power of 4?
- What elements of
c(3,4,5,6)
greater than 4?
Lists
Different from vectors, they allow us to put multiple structures in a list.
- Useful when we need to store a list of objects with different datatypes
Notice they are stored in two ‘different arrays’
as.vector
, as.list
can interchange list to vectors and vectors to list via as.vector and as.list
Exercise
- Generate a vector of 1 to 10, a list of characters 2.1 to 2.5 separated by 0.1
- Add the list to the vector and return a vector
- Define 2 vectors, x1, x2, by using rnorm(7,mean = 13, sd = 5)
- Do the inner product of x1,x2
Answer
Matrix
- Each column needs to contain same type.
- Like a high level vector.
Data Frames
- Generalised matrix. Now we can store different data types in different columns! =)
- Like high level list
Attributes
Attribute | Description |
---|---|
names |
Names of an object |
dimnames |
Names of the dimensions of an object |
dim |
Dimension of an object |
class |
Class of an object |
length |
Length of an object |
Data Manipulation
Indices, just like linear algebra, for vectors, specify thy entry, and matrix row first then column.
You can also Boolian values to get a subset of values:
Accessing the elements of a list is slightly different. Use double [[]]
notation:
Assigning names to data.frame and matrices
Adding new rows or columns into matrix or data.frame
rbind()
: Add new row to
rbind, cbind
Calling by Column Names
Reading csv/delim files
read.file_type(file = "Name.file_type", header = TRUE, sep = "")
Useful functions
apply, sapply, lapply
- sapply, lapply takes in vectors/list
- sapply(lapply) returns a vector(list) of same length
WARNING: DO NOT USE ANY OF lapply OR sapply under normal circumstances
Notice that this returns same thing as sapply, so there is no reason to use sapply under most of the cases.
apply
is a function to apply a function to a matrix by row or column or both
User define functions
Can predefine default value for argument(s) - Can take in vectors instead of scalars
Exercise
Use the iris dataset in R and build a matrix call iris.matrix with the followings:
1. Columns and rows of iris corresponds to columns and rows of iris.matrix
2. Change the Species column of iris.matrix into the following indicator variables
- 1 - setosa, 2 - versicolor, 3 - virginica
3. Get the mean of every column except for Species column
4. Take away respective mean from each column except for the Species column
5. Produce the summary of the new matrix
Futher Notes
browser()
is useful to help debugging, talk about this later?function_name
is useful to look up what a function does
Interesting reads:
ggplot2
: Plot package based around “the grammer of graphics”
data.table
: Package showcasing a faster version of data.frame
Next Steps:
R Programming Reference: http://rpubs.com/uwaterloodatateam/r-programming-reference
Contribute useful code snippets: https://github.com/uWaterlooDataTeam/r-programming-tutorial