While R and Rstudio are great tools in their own right, one of the greatest benefits is that anyone can create new tools for them. The standard way to share useful R code with other people is via the use of ‘R packages’; there are more than 7000 packages available by default, and more are made availabe all the time.
Conveniently, it’s possible to install new packages right from R/Rstudio!
An alternative to using the graphical menu is to simply use the “install.packages” function built into R. In the line below, we’ll install a package called “dplyr”, which is designed to simplify working with data frames.
install.packages("dplyr")
Packages will need to be installed on any computer you want to run your package-dependent code. For example, if you install a package on a computer in one of the university labs, R code which uses this package won’t run on your personal laptop until you also install the package there.
To use a package which has been installed, you need to use the “library” function. For example, if we’ve already installed the “dplyr” package, we can load it into our R session as follows:
library("dplyr")
## Warning: package 'dplyr' was built under R version 3.3.1
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
Sometimes, loading an R package will produce warning messages or information about other packages which have been loaded. If this annoys you, you can use the following optional argument to the “library” function:
library("dplyr", quietly = TRUE)
Note: you only need to install a package once per computer, don’t just leave a call to “install.packages” at the top of your script.
Go ahead and install the “dplyr” package on your computer, and download the following data sets:
Data is often messy, and in real life it’s almost never presented in a “ready to analyze” way. We don’t have time in this class to get into detailed data management tools,but there are a few techniques of which you should at least be aware; knowing where to turn for additional information is really helpful when solving complex real world problems.
The first example we’ll consider is the inventory system of a hypothetical bicycle shop. This particular shop keeps track of its inventory in two “tables”. One table keeps track of the brand, model, and quantity of bicycles currently in stock. The second table keeps track of what kind of bike each model is (this is obviously a toy, contrived example).
inventory <- data.frame(Brand = c("Surly",
"Surly",
"Surly",
"Trek",
"Giant",
"Specialized",
"Specialized"),
Model = c("Pacer",
"ICT",
"Pugsley",
"820",
"Escape",
"Roubaix",
"AWOL"),
Quantity = c(2,1,1,2,3,2,1))
model_types <- data.frame(Model = c("Pacer",
"Pugsley",
"820",
"Escape",
"Roubaix",
"AWOL"),
Type = c("road",
"fatbike",
"mountain",
"hybrid",
"road",
"touring"))
print(inventory)
## Brand Model Quantity
## 1 Surly Pacer 2
## 2 Surly ICT 1
## 3 Surly Pugsley 1
## 4 Trek 820 2
## 5 Giant Escape 3
## 6 Specialized Roubaix 2
## 7 Specialized AWOL 1
print(model_types)
## Model Type
## 1 Pacer road
## 2 Pugsley fatbike
## 3 820 mountain
## 4 Escape hybrid
## 5 Roubaix road
## 6 AWOL touring
The owner of this hypothetical bike shop wants to figure out how many bicycles of each type (road/mountain etc) she currently has on hand. As such, she needs to combine these two tables somehow. This operation is called a join in the dplyr package, and there are several ways to carry it out. One of the simplest is illustrated below:
merged_data <- inner_join(x = inventory, y = model_types, by = "Model")
print(merged_data)
## Brand Model Quantity Type
## 1 Surly Pacer 2 road
## 2 Surly Pugsley 1 fatbike
## 3 Trek 820 2 mountain
## 4 Giant Escape 3 hybrid
## 5 Specialized Roubaix 2 road
## 6 Specialized AWOL 1 touring
Now we have a data set which combines information from multiple component data sets, which is incredibly useful! Importantly, we need to pay attention to the way in which data sets are combined. In this case, we used an inner_merge, which means that we combine records from two input data sets based on a common variable, keeping only those records for which the common variable shows up in both input data sets. Take a close look at the join above; the Surly ICT doesn’t have an entry in the model_types table, so it doesn’t show up in the merged data set. To solve this issue, we can use what is known as a left_merge, which won’t throw away records in the first data set (which is listed on the left in code):
merged_data2 <- left_join(x = inventory, y = model_types, by = "Model")
print(merged_data2)
## Brand Model Quantity Type
## 1 Surly Pacer 2 road
## 2 Surly ICT 1 <NA>
## 3 Surly Pugsley 1 fatbike
## 4 Trek 820 2 mountain
## 5 Giant Escape 3 hybrid
## 6 Specialized Roubaix 2 road
## 7 Specialized AWOL 1 touring
Note that the Surly ICT now has a value of NA for “type” in the merged table, rather than being missing entirely.
Now we’re ready to summarize the data; namely, to count how many bicycles of each type are in the shop. This is accomplished by grouping the data set with the “group_by” function, and then asking for a summary of the grouped data:
grouped_data <- group_by(merged_data2, Type)
summary_data <- summarize(grouped_data, N = sum(Quantity))
print(summary_data)
## # A tibble: 6 x 2
## Type N
## <chr> <dbl>
## 1 fatbike 1
## 2 hybrid 3
## 3 mountain 2
## 4 road 4
## 5 touring 1
## 6 <NA> 1
In problem 4 of homework 2, we learned how to use indexing to reorder data in R. While this is an indispensable skill for data processing, in practice you may want to use a higher level tool.
I’ve posted (an augmented version of) the CSV file online, so you should be able to read it into R with the following code:
problem8 <- read.csv("http://goo.gl/icqFse")
print(problem8)
## Country PerCapita Continent
## 1 Australia 1032 Australia
## 2 Austria 1093 Europe
## 3 Belgium 980 Europe
## 4 Britain 836 Europe
## 5 Canada 1683 North America
## 6 Denmark 912 Europe
## 7 Finland 1067 Europe
## 8 France 1274 Europe
## 9 Germany 1232 Europe
## 10 Greece 371 Europe
## 11 Iceland 1353 Europe
## 12 Ireland 658 Europe
## 13 Italy 1050 Europe
## 14 Japan 1035 Asia
## 15 Luxembourg 1193 Europe
## 16 Netherlands 1135 Europe
## 17 New Zeland 820 Oceania
## 18 Norway 1234 Europe
## 19 Portugal 464 Europe
## 20 Spain 644 Europe
## 21 Sweden 1361 Europe
## 22 Switzerland 1376 Europe
## 23 United States 2354 North America
Since we’ve loaded the dplyr package, we can use the ‘arrange’ function it provides to sort the data automatically:
problem8.sorted <- arrange(problem8, PerCapita)
print(problem8.sorted)
## Country PerCapita Continent
## 1 Greece 371 Europe
## 2 Portugal 464 Europe
## 3 Spain 644 Europe
## 4 Ireland 658 Europe
## 5 New Zeland 820 Oceania
## 6 Britain 836 Europe
## 7 Denmark 912 Europe
## 8 Belgium 980 Europe
## 9 Australia 1032 Australia
## 10 Japan 1035 Asia
## 11 Italy 1050 Europe
## 12 Finland 1067 Europe
## 13 Austria 1093 Europe
## 14 Netherlands 1135 Europe
## 15 Luxembourg 1193 Europe
## 16 Germany 1232 Europe
## 17 Norway 1234 Europe
## 18 France 1274 Europe
## 19 Iceland 1353 Europe
## 20 Sweden 1361 Europe
## 21 Switzerland 1376 Europe
## 22 Canada 1683 North America
## 23 United States 2354 North America
Notice that the data set is now in the order we’d like!
In addition to sorting, we can also summarize this per-capita expenditure data by continent. We can even compute multiple summary statistics at the same time!
problem8.grouped <- group_by(problem8, Continent)
problem8.summary <- summarize(problem8.grouped,
TotalExpend = sum(PerCapita),
MaxExpend = max(PerCapita),
MinExpend = min(PerCapita),
MeanExpend = mean(PerCapita))
print(problem8.summary)
## # A tibble: 5 x 5
## Continent TotalExpend MaxExpend MinExpend MeanExpend
## <fctr> <int> <int> <int> <dbl>
## 1 Asia 1035 1035 1035 1035.000
## 2 Australia 1032 1032 1032 1032.000
## 3 Europe 18233 1376 371 1012.944
## 4 North America 4037 2354 1683 2018.500
## 5 Oceania 820 820 820 820.000
Unfortunately, these summary statistics aren’t particularly interesting, because the data included in the Pagano book is not a representative sample of nations around the globe:
table(problem8$Continent)
##
## Asia Australia Europe North America Oceania
## 1 1 18 2 1
As you can see, the data is very Euro-centric.
The two data sets we downloaded earlier were generated based on admissions data for incoming freshman at the University of Iowa. Before we can work with them, we’ll need to read them into R. Find out where you downloaded them (probably something like “C:/Users/
While we could read in the data directly from where you downloaded it, this is a good chance to get familiar with working directories. When R is running, it picks a folder called a “working directory” on your filesystem. This is kind of a “default location” where it will try to look for things, and save output. By default, it will probably pick your “Documents” folder, but this will vary. For example, if you opened Rstudio by double clicking on an R file, the working directory will be set to wherever that file happens to be located.
There’s no need to guess, however. We can get and set the working directory with the following commands:
wd <- getwd()
print(wd)
## [1] "H:/BIOS-4120/gh-pages/Labs/Lab3_Dplyr"
setwd(wd)
Alternatively, you can use the session menu at the top of Rstudio to choose “set working directory” to change it.
Note: on Microsoft Windows, folders are denoted with a backslash: “\”. R evolved in a Linux/Unix enviornment, where folders are denoted with a forward-slash, and backslashes are used to denote special characters. If you’re copying a folder path to R on a Windows machine, make sure to replace any backslashes with forward-slashes.
Once you’ve determined where your working directory is (or you’ve set it to a convenient location), move the downloaded data sets to that folder. We’re now ready to read in the files:
person <- read.csv("PersonData.csv", as.is = TRUE)
tests <- read.csv("TestData.csv", as.is = TRUE)
The first data set has two variables:
The second data set also has two variables:
Exercises:
Merge these two data sets using inner_merge. Find the average ACT score in each state.
Find the average ACT score for individuals who don’t show up in the “person” data set.