We will need the following packages:
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✔ ggplot2 3.3.6 ✔ purrr 0.3.4
## ✔ tibble 3.1.7 ✔ dplyr 1.0.9
## ✔ tidyr 1.2.0 ✔ stringr 1.4.0
## ✔ readr 2.1.2 ✔ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
library(gapminder)
library(datasets)
Using matrix operations to subset a tibble.
gapminder[gapminder$country == "Afghanistan" & gapminder$year > 1979,]
## # A tibble: 6 × 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Afghanistan Asia 1982 39.9 12881816 978.
## 2 Afghanistan Asia 1987 40.8 13867957 852.
## 3 Afghanistan Asia 1992 41.7 16317921 649.
## 4 Afghanistan Asia 1997 41.8 22227415 635.
## 5 Afghanistan Asia 2002 42.1 25268405 727.
## 6 Afghanistan Asia 2007 43.8 31889923 975.
gapminder[, c("country", "year", "lifeExp", "pop")]
## # A tibble: 1,704 × 4
## country year lifeExp pop
## <fct> <int> <dbl> <int>
## 1 Afghanistan 1952 28.8 8425333
## 2 Afghanistan 1957 30.3 9240934
## 3 Afghanistan 1962 32.0 10267083
## 4 Afghanistan 1967 34.0 11537966
## 5 Afghanistan 1972 36.1 13079460
## 6 Afghanistan 1977 38.4 14880372
## 7 Afghanistan 1982 39.9 12881816
## 8 Afghanistan 1987 40.8 13867957
## 9 Afghanistan 1992 41.7 16317921
## 10 Afghanistan 1997 41.8 22227415
## # … with 1,694 more rows
gapminder[gapminder$country == "Rwanda" &
gapminder$year > 1960 & gapminder$year < 1970,
c("country", "year", "lifeExp")]
## # A tibble: 2 × 3
## country year lifeExp
## <fct> <int> <dbl>
## 1 Rwanda 1962 43
## 2 Rwanda 1967 44.1
dplyr
approachselect(filter(gapminder, country == "Rwanda", year > 1960, year < 1970),
country, year, lifeExp)
## # A tibble: 2 × 3
## country year lifeExp
## <fct> <int> <dbl>
## 1 Rwanda 1962 43
## 2 Rwanda 1967 44.1
gapminder |>
filter(country == "Chile") |>
select(continent, year, lifeExp) |>
head(3)
## # A tibble: 3 × 3
## continent year lifeExp
## <fct> <int> <dbl>
## 1 Americas 1952 54.7
## 2 Americas 1957 56.1
## 3 Americas 1962 57.9
gapminder |>
filter(gdpPercap < 300, year < 2007) |>
select(country, year, gdpPercap)
## # A tibble: 3 × 3
## country year gdpPercap
## <fct> <int> <dbl>
## 1 Congo, Dem. Rep. 2002 241.
## 2 Guinea-Bissau 1952 300.
## 3 Lesotho 1952 299.