What we learned last week:
pacman)ggplot2)Some notes on the computational assignment and other more general notes:
x <- mean(mtcars$mpg)
x
## [1] 20.09062
.Rmd files don’t knit when your code has a line with
install.packages() in which you are installing a package
that already exists on your machine. Generally, you should only use
install.packages() in the console – after you’ve installed
a package once, it will exist on your computer forever. Many of you put
the install.packages("pacman") line in your
.Rmds and ran into knitting issues – after the initial
installation of pacman you only need to use
library(pacman) to load the pacman package,
and then simply use the p_load function to install/load
other packages you need.
Get started with your computational assignments early! There is no guarantee that I will be able to help you out if you run into issues on the day of the deadline.
If you have questions, you should: (1) come to my office hours; (2) if you can’t do (1) then you should send me an email in which you state a specific question or problem you are running into; (3) if you don’t have a specific question/problem and instead are simply confused/lost/unsure, then refer to (1) or email me to schedule a one-on-one meeting in which I can set you on the right track.
Please don’t email me an attachment of all of your work with the question ``Am I doing everything right?’’ :~) I can’t answer a general question like that for a variety of practical and ethical reasons.
Attend the labs or watch the full recording. Not every piece of necessary information will be given in these lab note documents – I might mention and demonstrate crucial concepts on the fly.
.csv FilesThe mtcars dataset comes pre-loaded with R for us to
play around with.
Suppose I want to save mtcars as a .csv
file on my computer.
I would use the write.csv function to do so.
The first input to this function is the data frame object in
question. The second input is the path for the .csv file
that is to be written (including the name of the file at the very
end).
# Save `mtcars` dataframe as `.csv` file
write.csv(mtcars, "C:/Users/gioni/Box/uo_phd_y3/spring_ec320/EC320s22/labs/02-working-with-data/data.csv")
In the above chunk, I’ve saved mtcars as a
.csv file called data.csv in a specific
directory (folder) on my computer.
Now, suppose I would like to import the data in data.csv
and store it in a dataframe called df in my current
instance of R.
I would use the read.csv function to do so.
# Import `data.csv` and store as data frame
df <- read.csv(file = "C:/Users/gioni/Box/uo_phd_y3/spring_ec320/EC320s22/labs/02-working-with-data/data.csv")
Let’s preview the new data frame df to convince
ourselves that the above code did its job:
df
## X mpg cyl disp hp drat wt qsec vs am gear carb
## 1 Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
## 2 Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
## 3 Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
## 4 Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
## 5 Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
## 6 Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
## 7 Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
## 8 Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
## 9 Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
## 10 Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
## 11 Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4
## 12 Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3
## 13 Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3
## 14 Merc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3
## 15 Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4
## 16 Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4
## 17 Chrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4
## 18 Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
## 19 Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
## 20 Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
## 21 Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1
## 22 Dodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2
## 23 AMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2
## 24 Camaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4
## 25 Pontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2
## 26 Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
## 27 Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
## 28 Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
## 29 Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4
## 30 Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6
## 31 Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8
## 32 Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2
The read.csv function automatically saves the dataset as
a data frame:
class(df)
## [1] "data.frame"
Alternatively, we could convert the data frame object df
to a “tibble”:
df <- as.tbl(df)
df
## # A tibble: 32 x 12
## X mpg cyl disp hp drat wt qsec vs am gear carb
## <fct> <dbl> <int> <dbl> <int> <dbl> <dbl> <dbl> <int> <int> <int> <int>
## 1 Mazda RX4 21 6 160 110 3.9 2.62 16.5 0 1 4 4
## 2 Mazda RX4 ~ 21 6 160 110 3.9 2.88 17.0 0 1 4 4
## 3 Datsun 710 22.8 4 108 93 3.85 2.32 18.6 1 1 4 1
## 4 Hornet 4 D~ 21.4 6 258 110 3.08 3.22 19.4 1 0 3 1
## 5 Hornet Spo~ 18.7 8 360 175 3.15 3.44 17.0 0 0 3 2
## 6 Valiant 18.1 6 225 105 2.76 3.46 20.2 1 0 3 1
## 7 Duster 360 14.3 8 360 245 3.21 3.57 15.8 0 0 3 4
## 8 Merc 240D 24.4 4 147. 62 3.69 3.19 20 1 0 4 2
## 9 Merc 230 22.8 4 141. 95 3.92 3.15 22.9 1 0 4 2
## 10 Merc 280 19.2 6 168. 123 3.92 3.44 18.3 1 0 4 4
## # ... with 22 more rows
Tibble is an extremely similar alternative object class to data frame
that is provided by the tidyverse package. We will not go
into details on tibble vs. data frame here, but the above was worth
showing since you are asked to convert a data frame object to a tibble
in your next computational assignment. For now, you can think of tibbles
and data frames as being interchangeable object classes.
If you have a large hierarchy of directories (folders) on your computer like I do, it may get cumbersome to keep typing out the full paths of datasets you want to import.
For this reason, it is useful give R directions on how to reach your desired dataset relative to your present working directory – this is the directory (folder) that R treats as an anchor (where R thinks you are currently “working”).
Find your current directory: getwd(). “wd” stands for
“working directory”.
getwd()
## [1] "C:/Users/gioni/Box/uo_phd_y3/spring_ec320/EC320s22/labs/02-working-with-data"
Show files in the current directory: dir()
dir()
## [1] "02-working-with-data.html" "02-working-with-data.Rmd"
## [3] "02-working-with-data_cache" "02-working-with-data_files"
## [5] "data.csv" "newfolder"
Change directory: setwd()
setwd("C:/Users/gioni/Box/uo_phd_y3/spring_ec320/EC320s22/labs/02-working-with-data/newfolder")
Notice that directories are characters (surrounded by
"").
RStudio will help you complete file paths when you hit tab while typing in the console.
You can save an object with the directory location and then return to
that directory using setwd().
Example:
my_dir <- "C:/Users/gioni/Box/uo_phd_y3/spring_ec320/EC320s22/labs/02-working-with-data"
setwd(my_dir)
Now let’s try importing the data.csv file relative to
our working directory:
df <- read.csv(file = "data.csv")
What if we wanted to write the data.csv file in the
newfolder subdirectory instead?
write.csv(mtcars, "newfolder/data.csv")
To import the above dataset:
df <- read.csv(file = "newfolder/data.csv")
The above paths to the .csv file relative to the current
working directory are called relative paths.
Data can be messy, or it can be tidy.
Tidy data has the following properties:
Messy data is any other arrangement of data. It can come in many forms, and usually needs to be thoroughly “cleaned” before it can be analyzed. Tidy data makes it easy for an analyst or a computer to extract needed variables because it provides a standard way of structuring a dataset.
gapmindergapminder is a dataset that lives in the
gapminder R package and contains data on countries’ total
population, GDP per capita, and life expectancy over time. The dataset
contains the following variables:
gdpPercap: GDP per capita of a country in a given
year.pop: Population of a country in a given year.lifeExp: Life expectancy in a country in a given
year.year: The year in which an observation was taken.continent: The continent to which a country associated
with a given observation belongs.country: The country with which a given observation is
associated.Let’s load the tidyverse and gapminder
packages to start working with this data.
library(pacman)
p_load(tidyverse, gapminder)
Print the dataset:
gapminder
## # A tibble: 1,704 x 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.
## # ... with 1,694 more rows
Print the first few observations of the dataset using the
head() function:
head(gapminder)
## # A tibble: 6 x 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.
Print the last few observations of the dataset using the
tail() function:
tail(gapminder)
## # A tibble: 6 x 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Zimbabwe Africa 1982 60.4 7636524 789.
## 2 Zimbabwe Africa 1987 62.4 9216418 706.
## 3 Zimbabwe Africa 1992 60.4 10704340 693.
## 4 Zimbabwe Africa 1997 46.8 11404948 792.
## 5 Zimbabwe Africa 2002 40.0 11926563 672.
## 6 Zimbabwe Africa 2007 43.5 12311143 470.
Print basic summary statistics on each of the variables contained by
the dataset using the summary() function:
summary(gapminder)
## country continent year lifeExp
## Afghanistan: 12 Africa :624 Min. :1952 Min. :23.60
## Albania : 12 Americas:300 1st Qu.:1966 1st Qu.:48.20
## Algeria : 12 Asia :396 Median :1980 Median :60.71
## Angola : 12 Europe :360 Mean :1980 Mean :59.47
## Argentina : 12 Oceania : 24 3rd Qu.:1993 3rd Qu.:70.85
## Australia : 12 Max. :2007 Max. :82.60
## (Other) :1632
## pop gdpPercap
## Min. :6.001e+04 Min. : 241.2
## 1st Qu.:2.794e+06 1st Qu.: 1202.1
## Median :7.024e+06 Median : 3531.8
## Mean :2.960e+07 Mean : 7215.3
## 3rd Qu.:1.959e+07 3rd Qu.: 9325.5
## Max. :1.319e+09 Max. :113523.1
##
Suppose we do not care about country population data.
Let’s the country, year, and
pop variables and store it all together in a new tibble
object called df_countrypop.
The tidyverse package provides us a handy function
called select that allows us to grab a select set of
variables from a data frame.
df_countrypop <- gapminder %>% select(country, year, pop)
df_countrypop
## # A tibble: 1,704 x 3
## country year pop
## <fct> <int> <int>
## 1 Afghanistan 1952 8425333
## 2 Afghanistan 1957 9240934
## 3 Afghanistan 1962 10267083
## 4 Afghanistan 1967 11537966
## 5 Afghanistan 1972 13079460
## 6 Afghanistan 1977 14880372
## 7 Afghanistan 1982 12881816
## 8 Afghanistan 1987 13867957
## 9 Afghanistan 1992 16317921
## 10 Afghanistan 1997 22227415
## # ... with 1,694 more rows
The pipe operator, written as %>%, takes the output
of one function and passes it into another function as an argument. This
allows us to link a sequence of analysis steps.
In the above code chunk, the pipe operator automatically gives
select() the gapminder tibble as an input, so
that select() knows that country,
year, and pop are columns that belong to
gapminder.
The pipe operator is extremely useful! Start playing around with it – you will rely on it heavily this quarter.
Alternatively (note that this is bad practice) you could have written
# DO NOT do the following in your code!!!
df_countrypop <- select(gapminder, country, year, pop) # This is bad.
df_countrypop
## # A tibble: 1,704 x 3
## country year pop
## <fct> <int> <int>
## 1 Afghanistan 1952 8425333
## 2 Afghanistan 1957 9240934
## 3 Afghanistan 1962 10267083
## 4 Afghanistan 1967 11537966
## 5 Afghanistan 1972 13079460
## 6 Afghanistan 1977 14880372
## 7 Afghanistan 1982 12881816
## 8 Afghanistan 1987 13867957
## 9 Afghanistan 1992 16317921
## 10 Afghanistan 1997 22227415
## # ... with 1,694 more rows
Now, suppose we only care about population data on the United States.
Let’s take the df_countrypop tibble we’ve just created and
filter for US-related data only using the filter()
function. Once again, we should use the pipe operator.
df_usapop <- df_countrypop %>% filter(country == "United States")
df_usapop
## # A tibble: 12 x 3
## country year pop
## <fct> <int> <int>
## 1 United States 1952 157553000
## 2 United States 1957 171984000
## 3 United States 1962 186538000
## 4 United States 1967 198712000
## 5 United States 1972 209896000
## 6 United States 1977 220239000
## 7 United States 1982 232187835
## 8 United States 1987 242803533
## 9 United States 1992 256894189
## 10 United States 1997 272911760
## 11 United States 2002 287675526
## 12 United States 2007 301139947
The above sequence of steps is equivalent to having done the following in one go:
df_usapop <- gapminder %>%
select(country, year, pop) %>%
filter(country == "United States")
Note the use of == inside of filter in the
above code chunk. A single equal sign = acts as an
assignment operator, while the double equal sign == is a
relational operator that yields “TRUE” if two objects
are equal and “FALSE” otherwise.
The filter(country == "United States") command basically
skims through all observations inside of the
gapminder %>% select(country, year, pop) dataset and for
each observation says “if the value of the country variable
in this observation is equal to”United States”, then keep this
observation – if not, then discard this observation”. Or equivalenty “if
country == "United States" is true for this observation,
then keep it – discard otherwise.”
Let’s quickly plot the data we’ve gathered in
df_usapop:
ggplot(df_usapop, aes(x = year, y = pop)) +
geom_line()
We can easily create a new column of data and add it to
df_usapop by transforming the existing columns.
For example, suppose we want to express the total population values
pop in millions and store it in a new column called
popmil:
df_usapop <- df_usapop %>%
mutate(popmil = pop/1000000)
df_usapop
## # A tibble: 12 x 4
## country year pop popmil
## <fct> <int> <int> <dbl>
## 1 United States 1952 157553000 158.
## 2 United States 1957 171984000 172.
## 3 United States 1962 186538000 187.
## 4 United States 1967 198712000 199.
## 5 United States 1972 209896000 210.
## 6 United States 1977 220239000 220.
## 7 United States 1982 232187835 232.
## 8 United States 1987 242803533 243.
## 9 United States 1992 256894189 257.
## 10 United States 1997 272911760 273.
## 11 United States 2002 287675526 288.
## 12 United States 2007 301139947 301.
Let’s visual popmil now as a timeplot.
ggplot(df_usapop, aes(x = year, y = popmil)) +
geom_line()
Now let’s focus on the life expectancy data of all countries in the
year 1992. We can easily gather the above data in a new object called
df_lifeExp92 using some of the tools we’ve learned so
far:
df_lifeExp92 <- gapminder %>%
select(country, year, lifeExp) %>%
filter(year == 1992)
df_lifeExp92
## # A tibble: 142 x 3
## country year lifeExp
## <fct> <int> <dbl>
## 1 Afghanistan 1992 41.7
## 2 Albania 1992 71.6
## 3 Algeria 1992 67.7
## 4 Angola 1992 40.6
## 5 Argentina 1992 71.9
## 6 Australia 1992 77.6
## 7 Austria 1992 76.0
## 8 Bahrain 1992 72.6
## 9 Bangladesh 1992 56.0
## 10 Belgium 1992 76.5
## # ... with 132 more rows
We may use the arrange() function to order all of the
observations in df_lifeExp92 in increasing order with
respect to the values in lifeExp.
df_lifeExp92 <- df_lifeExp92 %>%
arrange(lifeExp)
df_lifeExp92
## # A tibble: 142 x 3
## country year lifeExp
## <fct> <int> <dbl>
## 1 Rwanda 1992 23.6
## 2 Sierra Leone 1992 38.3
## 3 Somalia 1992 39.7
## 4 Angola 1992 40.6
## 5 Liberia 1992 40.8
## 6 Afghanistan 1992 41.7
## 7 Guinea-Bissau 1992 43.3
## 8 Mozambique 1992 44.3
## 9 Burundi 1992 44.7
## 10 Congo, Dem. Rep. 1992 45.5
## # ... with 132 more rows
Similarly, we may us ethe desc() function inside of
arrange() to order the observations in decreasing order
with respect to lifeExp.
df_lifeExp92 <- df_lifeExp92 %>%
arrange(desc(lifeExp))
df_lifeExp92
## # A tibble: 142 x 3
## country year lifeExp
## <fct> <int> <dbl>
## 1 Japan 1992 79.4
## 2 Iceland 1992 78.8
## 3 Sweden 1992 78.2
## 4 Switzerland 1992 78.0
## 5 Canada 1992 78.0
## 6 Hong Kong, China 1992 77.6
## 7 Spain 1992 77.6
## 8 Australia 1992 77.6
## 9 France 1992 77.5
## 10 Italy 1992 77.4
## # ... with 132 more rows