31 * 12) / 2^4 (
[1] 23.25
January 23, 2024
Logical equality and inequality (yielding a TRUE
or FALSE
result) is done with ==
and !=
. Other logical operators include <
, >
, <=
, >=
, and !
for negation.
Here’s a gotcha. You might think you could write 3 < 5 & 7
and have it be interpreted as “Three is less than five and also less than seven [True or False?]”:
It seems to work!
But now try 3 < 5 & 1
, where your intention is “Three is less than five and also less than one [True or False?]”
3 < 5
is evaluated first, and resolves to TRUE, leaving us with the expression TRUE
& 1
.TRUE
& as.logical(1)
.1
resolves to TRUE
. Any other number is FALSE
. So,Let’s evaluate 0.6 + 0.2 == 0.8
Let’s evaluate 0.6 + 0.2 == 0.8
Let’s evaluate 0.6 + 0.2 == 0.8
Now let’s try 0.6 + 0.3 == 0.9
Let’s evaluate 0.6 + 0.2 == 0.8
Now let’s try 0.6 + 0.3 == 0.9
Er. That’s not right.
In Base 10, you can’t precisely express fractions like \(\frac{1}{3}\) and \(\frac{1}{9}\). They come out as repeating decimals: 0.3333… or 0.1111… You can cleanly represent fractions that use a prime factor of the base, which in the case of Base 10 are 2 and 5.
In Base 10, you can’t precisely express fractions like \(\frac{1}{3}\) and \(\frac{1}{9}\). They come out as repeating decimals: 0.3333… or 0.1111… You can cleanly represent fractions that use a prime factor of the base, which in the case of Base 10 are 2 and 5.
Computers represent numbers as binary (i.e. Base 2) floating-points. In Base 2, the only prime factor is 2. So \(\frac{1}{5}\) or \(\frac{1}{10}\) in binary would be repeating.
When you do binary math on repeating numbers and convert back to decimals you get tiny leftovers, and this can mess up logical comparisons of equality. The all.equal()
function exists for this purpose.
[1] 0.3
[1] 0.300000000000000044
[1] TRUE
See e.g. https://0.30000000000000004.com
More later on why this might bite you, and how to deal with it
[1] 1 1 2 4 1 3 1 5
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[20] "T" "U" "V" "W" "X" "Y" "Z"
[1] 3.141593
Or it’s a really bad idea to try to use them
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"
Functions (more about which in a second) are objects too. Type their name at the console to look inside.
In fact, this is mostly what we will be doing.
Objects are created by assigning a thing to a name:
The c()
function combines or concatenates things
The assignment operator performs the action of creating objects
Use a keyboard shortcut to write it:
Press option
and -
on a Mac
Press alt
and -
on Windows
=
You can use =
as well as <-
for assignment.
On the other hand, =
has a different meaning when used in functions.
I’m going to use <-
for assignment throughout.
Just be consistent either way.
=
Functions can be identified by the parentheses after their names.
=
my_numbers)=
my_numbers)If you don’t name the arguments, R assumes you are providing them in the order the function expects.
What arguments? Which order? Read the function’s help page
Arguments often tell the function what to do in specific circumstances
[1] NA
[1] 32.44444
Or select from one of several options
There are all kinds of functions. They return different things.
You can assign the output of a function to a name, which turns it into an object. (Otherwise it’ll send its output to the console.)
Objects hang around in your work environment until they are overwritten by you, or are deleted.
Nested functions are evaluated from the inside out.
Instead of deeply nesting functions in parentheses, we can use the pipe operator:
Read this operator as “and then”
Better, vertical space is free in R:
See how the first thing you read is the last operation performed.
We can use vertical space and indents, but it’s really not much better:
Much nicer:
eggs |>
get_from_fridge() |>
crack_eggs(into = "bowl") |>
whisk(len = 40) |>
pour_in_pan(temp = "med-high") |>
stir() |>
serve()
We’ll still use nested parentheses quite a bit, often in the context of a function working inside a pipeline. But it’s good not to have too many levels of nesting.
%>%
The Base R pipe operator, |>
is a relatively recent addition to R.
Piping operations were originally introduced in a package called called magrittr
, where it took the form %>%
%>%
The Base R pipe operator, |>
is a relatively recent addition to R.
Piping operations were originally introduced in a package called called magrittr
, where it took the form %>%
It’s been so successful, a version of it has been incorporated into Base R. It mostly but does not quite work the same way as %>%
in every case.
%>%
The Base R pipe operator, |>
is a relatively recent addition to R.
Piping operations were originally introduced in a package called called magrittr
, where it took the form %>%
It’s been so successful, a version of it has been incorporated into Base R. It mostly but does not quite work the same way as %>%
in every case. We’ll use the Base R pipe in this course, but you’ll see the Magrittr pipe a lot out in the world.
Why %>%
? In R the notation %<SOMETHING>%
is used for some operators, including custom operators.
Why %>%
? In R the notation %<SOMETHING>%
is used for some operators, including custom operators. E.g., matrix multiplication is %*%
But the thing in between the % %
can be lots of things. E.g.,
And we can define our own, too
Packages are loaded into your working environment using the library()
function:
# A tibble: 1,704 × 6
country continent year lifeExp pop gdpPercap
<fct> <fct> <int> <dbl> <int> <dbl>
1 Afghanistan Asia 1952 28.8 8425333 779.
2 Afghanistan Asia 1957 30.3 9240934 821.
3 Afghanistan Asia 1962 32.0 10267083 853.
4 Afghanistan Asia 1967 34.0 11537966 836.
5 Afghanistan Asia 1972 36.1 13079460 740.
6 Afghanistan Asia 1977 38.4 14880372 786.
7 Afghanistan Asia 1982 39.9 12881816 978.
8 Afghanistan Asia 1987 40.8 13867957 852.
9 Afghanistan Asia 1992 41.7 16317921 649.
10 Afghanistan Asia 1997 41.8 22227415 635.
# ℹ 1,694 more rows
You need only install a package once (and occasionally update it):
But you must load the package in each R session before you can access its contents:
## To load a package, usually at the start of your RMarkdown document or script file
library(palmerpenguins)
penguins
# A tibble: 344 × 8
species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
<fct> <fct> <dbl> <dbl> <int> <int>
1 Adelie Torgersen 39.1 18.7 181 3750
2 Adelie Torgersen 39.5 17.4 186 3800
3 Adelie Torgersen 40.3 18 195 3250
4 Adelie Torgersen NA NA NA NA
5 Adelie Torgersen 36.7 19.3 193 3450
6 Adelie Torgersen 39.3 20.6 190 3650
7 Adelie Torgersen 38.9 17.8 181 3625
8 Adelie Torgersen 39.2 19.6 195 4675
9 Adelie Torgersen 34.1 18.1 193 3475
10 Adelie Torgersen 42 20.2 190 4250
# ℹ 334 more rows
# ℹ 2 more variables: sex <fct>, year <int>
::
“Reach in” to an unloaded package and grab a function directly, using <package>::<function>
::
## A little glimpse of what we'll do soon
penguins |>
select(species, body_mass_g, sex) |>
gtsummary::tbl_summary(by = species)
Characteristic | Adelie, N = 152 | Chinstrap, N = 68 | Gentoo, N = 124 |
---|---|---|---|
body_mass_g, Median (IQR) | 3,700 (3,350 – 4,000) | 3,700 (3,488 – 3,950) | 5,000 (4,700 – 5,500) |
Unknown | 1 | 0 | 1 |
sex, n (%) | |||
female | 73 (50) | 34 (50) | 58 (49) |
male | 73 (50) | 34 (50) | 61 (51) |
Unknown | 6 | 0 | 5 |
I’m going to speak somewhat loosely here for now, and gloss over some distinctions between object classes and data structures, as well as kinds of objects and their attributes.
I’m going to speak somewhat loosely here for now, and gloss over some distinctions between object classes and data structures, as well as kinds of objects and their attributes.
The object inspector in RStudio is your friend.
You can ask an object what it is at the console, too:
Objects can have more than one (nested) class:
Min. 1st Qu. Median Mean 3rd Qu. Max.
1.00 1.75 3.00 6.25 6.25 25.00
my_smry <- summary(my_numbers) # remember, outputs can be assigned to a name, creating an object
class(summary(my_numbers)) # functions can be nested, and are evaluated from the inside out
[1] "summaryDefault" "table"
[1] "summaryDefault" "table"
[1] "double"
$names
[1] "Min." "1st Qu." "Median" "Mean" "3rd Qu." "Max."
$class
[1] "summaryDefault" "table"
[1] "summaryDefault" "table"
[1] "Min." "1st Qu." "Median" "Mean" "3rd Qu." "Max."
## Factors are for storing undordered or ordered categorical variables
x <- factor(c("Yes", "No", "No", "Maybe", "Yes", "Yes", "Yes", "No"))
x
[1] Yes No No Maybe Yes Yes Yes No
Levels: Maybe No Yes
Maybe No Yes
1 3 4
[1] "integer"
$levels
[1] "Maybe" "No" "Yes"
$class
[1] "factor"
[1] "Maybe" "No" "Yes"
[1] FALSE
# A tibble: 1,704 × 6
country continent year lifeExp pop gdpPercap
<fct> <fct> <int> <dbl> <int> <dbl>
1 Afghanistan Asia 1952 28.8 8425333 779.
2 Afghanistan Asia 1957 30.3 9240934 821.
3 Afghanistan Asia 1962 32.0 10267083 853.
4 Afghanistan Asia 1967 34.0 11537966 836.
5 Afghanistan Asia 1972 36.1 13079460 740.
6 Afghanistan Asia 1977 38.4 14880372 786.
7 Afghanistan Asia 1982 39.9 12881816 978.
8 Afghanistan Asia 1987 40.8 13867957 852.
9 Afghanistan Asia 1992 41.7 16317921 649.
10 Afghanistan Asia 1997 41.8 22227415 635.
# ℹ 1,694 more rows
[1] "tbl_df" "tbl" "data.frame"
[1] "list"
Lists can be heterogenous. Underneath, most complex R objects are some kind of list with different components.
A data frame is a list of vectors of the same length, where the vectors can be of different types (e.g. numeric, character, logical, etc)
A tibble is an enhanced data frame
data.frame
fate sex n percent
1 perished male 1364 62.0
2 perished female 126 5.7
3 survived male 367 16.7
4 survived female 344 15.6
[1] "data.frame"
data.frame
fate sex n percent
1 perished male 1364 62.0
2 perished female 126 5.7
3 survived male 367 16.7
4 survived female 344 15.6
[1] "data.frame"
tibble
# A tibble: 2,867 × 32
year id ballot age childs sibs degree race sex region income16
<dbl> <dbl> <labelled> <dbl> <dbl> <labe> <fct> <fct> <fct> <fct> <fct>
1 2016 1 1 47 3 2 Bache… White Male New E… $170000…
2 2016 2 2 61 0 3 High … White Male New E… $50000 …
3 2016 3 3 72 2 3 Bache… White Male New E… $75000 …
4 2016 4 1 43 4 3 High … White Fema… New E… $170000…
5 2016 5 3 55 2 2 Gradu… White Fema… New E… $170000…
6 2016 6 2 53 2 2 Junio… White Fema… New E… $60000 …
7 2016 7 1 50 2 2 High … White Male New E… $170000…
8 2016 8 3 23 3 6 High … Other Fema… Middl… $30000 …
9 2016 9 1 45 3 5 High … Black Male Middl… $60000 …
10 2016 10 3 71 4 1 Junio… White Male Middl… $60000 …
# ℹ 2,857 more rows
# ℹ 21 more variables: relig <fct>, marital <fct>, padeg <fct>, madeg <fct>,
# partyid <fct>, polviews <fct>, happy <fct>, partners <fct>, grass <fct>,
# zodiac <fct>, pres12 <labelled>, wtssall <dbl>, income_rc <fct>,
# agegrp <fct>, ageq <fct>, siblings <fct>, kids <fct>, religion <fct>,
# bigregion <fct>, partners_rc <fct>, obama <dbl>
In R, all numbers are vectors of different sorts. Even single numbers (“scalars”) are conceptually vectors of length 1.
Arithmetic on vectors (and arrays generally) follows a series of recycling rules that favor ease of expression of vectorized, “elementwise” operations.
See if you can predict what the following operations do:
Warning in my_numbers + three_nums: longer object length is not a multiple of
shorter object length
Note that you get a warning here. It’ll still do it, though! Don’t ignore warnings until you understand what they mean.