Handout 02
Date: 2022-09-22
Topics: R basics; Visualization
Literature
Handout
Ismay & Kim (2022) Preface and Chapter 1
Read Ismay & Kim (2022), section 1.2.1
| Operator | Operation | Example |
|---|---|---|
| + | Addition | 12 + 5 |
| - | Subtraction | 90 - 78 |
| * | Multiplication | 23 * 4 |
| / | Division | 18 / 4 |
| ^ | Exponent | 2^5 |
Note. The spaces are not required.
Example Code 1
a <- 250
b <- 200
c <- a + b
c
## [1] 450
Example Code 2
p <- c(20, 25, 30, 40, 50) #prices of tickets for different categories
q <- c(200, 150, 200, 100, 100) #number of tickets sold for each category
rev <- p*q
rev_total <- sum(rev) #rev_total <- sum(p*q) works as well
rev
## [1] 4000 3750 6000 4000 5000
rev_total
## [1] 22750
Try out the examples in the table below.
| Operator | Operation | Example |
|---|---|---|
| > | Greater than | 25 > 30 |
| < | Less then | 25 < 30 |
| >= | Greater than or equal to | 25 >= 30 |
| <= | Less than or equal to | 25 <= 30 |
| == | Equal to | 25 == 30 |
| != | Is not equal to | 25 != 30 |
Example code
x <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) # or shorter x <- 1:10
x > 7
## [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE
x == 9
## [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE
x != 12
## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
Try out the examples in the table below.
| Operator | Operation | Example |
|---|---|---|
| & | AND | 25 < 30 & 10 > 12 |
| | | OR | 25 < 30 | 10 > 12 ; 25 < 30 | 10 < 12 |
Try out the examples in the table below.
| Function | Function | Examples |
|---|---|---|
| sqrt(x) | Square Root | sqrt(50) |
| abs(x) | Absolute Value | abs(12.5) ; abs(-12.5) |
| floor(x) | Round down to nearest integer | floor(3.75); floor(-3.75) |
| ceiling(x) | Round up to nearest integer | ceiling(3.75); ceiling(-3.75) |
| round(x, digits=0) | Round the argument to the specified number of decimal places, default is 0 | round(2.34, digits = 1) |
Try out the examples in the table below.
| Function | Examples |
|---|---|
| is.numeric(x) | is.numeric(123); is.numeric(“123”); is.numeric(“eight”); is.numeric(eight) |
| is.character | is.character(123); is.character(“123”); is.character(“eight”) |
Ismay & Kim (2022), section 1.3
Essential Packages
Ismay & Kim (2022), section 1.4
Work through the examples in this section, using your own data set or
using the nycflights13 data set.
Some take aways from the first sessions.
R can handle a great number of datafile formats. Which function to use to import a file depends on the file format. Some options for common formats.
There are many more options. If a file in an other file format must be imported, Google to find an R function to do the job.
Some rules for naming objects and variables.
Commonly used options for longer names. This applies to file names, to object names and to variable names.