Learning Objectives
- Load external data from a .csv file into a data frame.
- Install and load packages.
- Summarize the contents of a data frame.
- Use indexing to subset specific portions of data frames.
- Convert between strings and factors, and reorder and rename factors.
- Format dates.
For this exercise, we will use the Portal Project Teaching Database (Ernest et al. 2018). The data were collected to investigate animal species diversity and weights found within plots at the authors’ study site in Portal, AZ, USA. The dataset is stored as a comma separated value (CSV) file. Each row holds information for a single animal, and the columns represent:
| Column | Description |
|---|---|
| record_id | Unique id for the observation |
| month | month of observation |
| day | day of observation |
| year | year of observation |
| plot_id | ID of a particular experimental plot of land |
| species_id | 2-letter code |
| sex | sex of animal (<93>M<94>, <93>F<94>) |
| hindfoot_length | length of the hindfoot in mm |
| weight | weight of the animal in grams |
| genus | genus of animal |
| species | species of animal |
| taxon | e.g. |
| plot_type | type of plo |
The first step, before you download data or begin scripting any code, is to open your Environmental Data Analysis project. This will ensure that R is looking for files in the appropriate working directory, and saving files to the appropriate location in your project folder. If you haven’t already, login to Google Desktop, and open your project in RStudio (File -> Open project, or select Open project from the dropdown menu in the upper right corner of RStudio). Now is also a good time to open a new script for this workshop and save it as something appropriate, e.g., “A02 Getting Started with Data.”
We created the folder that will store the downloaded data
(data_raw) in the last unit. If you skipped that part, it
may be a good idea to have a look now, to make sure your working
directory is set up properly.
We are going to use the R function download.file() to
download the CSV file that contains the survey data from figshare, and
we will use read_csv() to load the content of the CSV file
into R.
Inside the download.file command, the first entry is a character
string with the source URL (“https://ndownloader.figshare.com/files/2292169”). This
source URL downloads a CSV file from figshare. The text after the comma
(“data_raw/portal_data_joined.csv”) is the destination of the file on
your local machine. You’ll need to have a folder on your machine called
data_raw where you’ll download the file. This command
downloads a file from figshare, names it
portal_data_joined.csv and adds it to a preexisting folder
named data_raw.
download.file(url = "https://ndownloader.figshare.com/files/2292169",
destfile = "data_raw/portal_data_joined.csv")
If you are working on a personal computer with an internet
connection, this command should download the data file to your
data_raw folder, and you should see it there now.
If you are working on a computer in Hudson, this may or may not
have worked, depending on the security settings. (IT doesn’t
like us downloading files directly from a remote server…go figure.) No
worries! You can manually download the data file
portal_data_joined.csv from the course Brightspace site,
and drag it to your data_raw folder. To be fair, this is
how I work with data files most of the time because I am typically
creating them on my computer or downloading them from a shared drive, an
email, a scientific instrument, or a government database that doesn’t
support these types of data queries.
The file has now been downloaded to the destination you specified,
but R has not yet loaded the data from the file into memory.
(i.e., the data do not yet exist as an object in your
Environment.) You can read data in using the read.csv()
function, which comes with a basic R installation. However, we will use
the read_csv() function from the tidyverse
package because it loads large datasets faster and has other benefits
(e.g., supports non-standard variable names, never creates row
names, doesn’t make strange programmatic assumptions about input types,
etc.). Notice that the exact spelling of the function will
determine which function is called!
To use the read_csv() function, we will first need to
install and load the tidyverse package.
Packages in R are basically sets of additional functions that let you
do more stuff. The functions we’ve been using so far, like
round(), sqrt(), or c() come
built into R. Packages give you access to additional functions beyond
base R. Before you use a package for the first time you need to install
it on your machine, and then you should import it in every subsequent R
session when you need it.
If you are working on a Hudson computer, tidyverse
should already be installed, so you can skip this step. But it’s good to
know how to install a package because you will need to do so at some
point in the future.
To install the tidyverse package, we can type
install.packages("tidyverse") straight into the console. In
fact, it’s usually better to install packages from the console than in a
script, as there’s no need to re-install packages every time we run the
script. If you do install your package from the script, you should
comment out that line once the install is complete (i.e., place
a # at the front of the line so it doesn’t run again).
install.packages("tidyverse")
Then, to load the package type:
## load the tidyverse packages, incl. dplyr
library(tidyverse)
Note: You will need to run the
library()function to load the packages you are going to use every time you start a new R session. It’s good practice to keep all the packages you will need to load to run a script at the top of the script file in a section labeled# Packages.
Now that we have installed the tidyverse package, we can
use read_csv() to read the Portal data into a data frame.
We will name the data frame object surveys.
surveys <- read_csv("data_raw/portal_data_joined.csv")
## Rows: 34786 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (6): species_id, sex, genus, species, taxa, plot_type
## dbl (7): record_id, month, day, year, plot_id, hindfoot_length, weight
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
When you execute read_csv on a data file, it looks
through the first 1000 rows of each column and guesses its data type.
For example, in this dataset, read_csv() reads
weight as col_double (a numeric
data type), and species as col_character. You
have the option to specify the data type for a column manually by using
the col_types argument in read_csv.
Note:
read_csv()assumes that fields are delineated by commas. However, in several countries, the comma is used as a decimal separator and the semicolon (;) is used as a field delineator. If you want to read in this type of files in R, you can use theread_csv2()function. It behaves likeread_csv()but uses different parameters for the decimal and the field separators. There is also theread_tsv()for tab separated data files andread_delim()for less common formats. Check out the help forread_csv()by typing?read_csvto learn more.
We can see the contents of the first few lines of the data by typing
its name: surveys. By default, this will show you as many
rows and columns of the data as fit on your screen. If you wanted the
first 50 rows, you could type print(surveys, n = 50)
We can also extract the first few lines of this data using the function
head():
head(surveys)
## # A tibble: 6 × 13
## record_id month day year plot_id speci…¹ sex hindf…² weight genus species
## <dbl> <dbl> <dbl> <dbl> <dbl> <chr> <chr> <dbl> <dbl> <chr> <chr>
## 1 1 7 16 1977 2 NL M 32 NA Neot… albigu…
## 2 72 8 19 1977 2 NL M 31 NA Neot… albigu…
## 3 224 9 13 1977 2 NL <NA> NA NA Neot… albigu…
## 4 266 10 16 1977 2 NL <NA> NA NA Neot… albigu…
## 5 349 11 12 1977 2 NL <NA> NA NA Neot… albigu…
## 6 363 11 12 1977 2 NL <NA> NA NA Neot… albigu…
## # … with 2 more variables: taxa <chr>, plot_type <chr>, and abbreviated
## # variable names ¹species_id, ²hindfoot_length
Unlike the print() function, head() returns
the extracted data. You could use it to assign the first 100 rows of
surveys to an object using
surveys_sample <- head(surveys, 100). This can be useful
if you want to try out complex computations on a subset of your data
before you apply them to the whole data set. There is a similar function
that lets you extract the last few lines of the data set. It is called
(you might have guessed it) tail().
To open the dataset in RStudio’s Data Viewer, use the
view() function:
view(surveys)
You can also open your dataset in the Data Viewer by clicking on the data frame object in the Environment pane.
Note: There are two functions for viewing, which are case-sensitive. Using
view()with a lowercase ‘v’ is part oftidyverse, whereas usingView()with an uppercase ‘V’ is loaded through base R in theutilspackage. You can also open your dataset in the Data Viewer by clicking on the data frame object in the Environment pane. This runs theView()function on that object.
When we loaded the data into R, it got stored as an object of class
tibble, which is a special kind of data frame (the
difference is not important for our purposes, but you can learn more
about tibbles here). Data
frames are the de facto data structure for most tabular data,
and what we use for statistics and plotting. Data frames can be created
by hand, but most commonly they are generated by functions like
read_csv(); in other words, when importing spreadsheets
from your hard drive or the web.
A data frame is the representation of data in the format of a table where the columns are vectors that all have the same length. Because columns are vectors, each column must contain a single type of data (e.g., characters, integers, factors). For example, here is a figure depicting a data frame comprising a numeric, a character, and a logical vector.
We can see this also when inspecting the structure of a
data frame with the function str():
str(surveys)
Run the str() function and look at the output. What is
the class of object surveys? How many rows and how many
columns are in this object?
We already saw how the functions head() and
str() can be useful to check the content and the structure
of a data frame. Here is a non-exhaustive list of functions to get a
sense of the content/structure of the data. Let’s try them out!
dim(surveys) - returns a vector with the number of rows
in the first element, and the number of columns as the second element
(the dimensions of the object)nrow(surveys) - returns the number of rowsncol(surveys) - returns the number of columnshead(surveys) - shows the first 6 rowstail(surveys) - shows the last 6 rowsnames(surveys) - returns the column names (synonym of
colnames() for data.frame objects)rownames(surveys) - returns the row namesstr(surveys) - structure of the object and information
about the class, length and content of each columnsummary(surveys) - summary statistics for each
columnMost of these functions are “generic,” meaning they can be used for other types of objects besides data frames.
Just as we did with vectors, we will use square brackets for indexing
[], or extracting specific data from an object. Vectors
have only one dimension, so we only needed to specify one coordinate to
extract values from a vector, e.g., num[4] to
extract the fourth position of vector num.
Our survey data frame has two dimensions: rows and columns. If we want to extract some specific data from it, we need to specify the “coordinates” we want from it. Row numbers come first, followed by column numbers, separated by a comma. We can extract specific values by specifying row and column indices in the format: data_frame[row_index, column_index]
# For instance, to extract the first row and column from surveys:
surveys[1, 1]
# First row, sixth column:
surveys[1, 6]
We can also use shortcuts to select a number of rows or columns at once. To select all columns, leave the column index blank. The same shortcut works to select all rows for certain columns.
# For instance, to select all columns for the first row:
surveys[1, ]
# To select the first column across all rows:
surveys[, 1]
# An even shorter way to select first column across all rows:
surveys[1] # No comma!
To select multiple rows or columns, you can use the
c() function to create a vector that identifies the
positions you want. If we want all rows or columns within a range, we
can use the : function. : is a special
function that creates numeric vectors of integers in increasing or
decreasing order, test 1:10 and 10:1 for instance.
# To select the first three rows of the 5th and 6th column
surveys[c(1, 2, 3), c(5, 6)]
# We can use the : operator to create those vectors for us:
surveys[1:3, 5:6]
# This is equivalent to head_surveys <- head(surveys)
head_surveys <- surveys[1:6, ]
Note that different ways of specifying these coordinates lead to
results with different classes. For example, subsetting
a data frame with single square brackets [] always returns
a data frame (even if it only has a single value). If you would like to
create a vector from a dataframe, use double square brackets
[[]].
# For instance, to get the first column as a vector:
surveys[[1]]
# To get the first value in our data frame:
surveys[[1, 1]]
You can also exclude certain indices of a data frame
using the “-” sign:
surveys[, -1] # The whole data frame, except the first column
surveys[-(7:nrow(surveys)), ] # Equivalent to head(surveys)
Data frames can be subset by calling indices (as shown previously),
but also by calling their column names directly. As
before, single brackets return a data frame, and double brackets return
a vector. We can also use the $ operator
to call a column from a dataframe, e.g.,
surveys$species_id. This notation is very useful when you
want to reorder, rename, or transform a variable. It’s also very useful
for creating new calculated columns, which we will cover later in the
course.
# As before, using single brackets returns a data frame:
surveys["species_id"]
surveys[, "species_id"]
# Double brackets returns a vector:
surveys[["species_id"]]
# We can also use the $ operator with column names instead of double brackets
# This returns a vector:
surveys$species_id
In RStudio, you can use the autocompletion feature to get the full and correct names of the columns.
When we ran str(surveys) we saw that several of the
columns consist of integers. The columns genus,
species, sex, plot_type, however,
are of the class character. Arguably, these columns contain
categorical data, that is, they can only take on a limited number of
values.
R has a special class for working with categorical data, called
factor. Factors are very useful and
actually contribute to making R particularly well suited to working with
data. So we are going to spend a little time introducing them.
Once created, factors can only contain a pre-defined set of values, known as levels. Factors are stored as integers associated with labels and they can be ordered or unordered. While factors look (and often behave) like character vectors, they are actually treated as integer vectors by R. So you need to be very careful when treating them as strings.
When importing a data frame with read_csv(), the columns
that contain text are not automatically coerced (i.e.,
converted) into the factor data type, but once we have
loaded the data we can do the conversion using the factor()
function:
surveys$sex <- factor(surveys$sex)
We can see that the conversion has worked by using the
summary() function again. This produces a table with the
counts for each factor level:
summary(surveys$sex)
## F M NA's
## 15690 17348 1748
By default, R always sorts levels in alphabetical order. For instance, if you have a factor with 2 levels:
sex <- factor(c("male", "female", "female", "male"))
R will assign 1 to the level "female" and
2 to the level "male" (because f
comes before m, even though the first element in this
vector is "male"). You can see this by using the function
levels() and you can find the number of levels using
nlevels():
levels(sex)
nlevels(sex)
Sometimes, the order of the factors does not matter, other times you might want to specify the order because it is meaningful (e.g., “low”, “medium”, “high”), it improves your visualization, or it is required by a particular type of analysis. Here, one way to reorder our levels in the sex vector would be:
sex # current order
## [1] male female female male
## Levels: female male
sex <- factor(sex, levels = c("male", "female"))
sex # after reordering
## [1] male female female male
## Levels: male female
In R’s memory, these factors are represented by integers (1, 2, 3),
but are more informative than integers because factors are self
describing: "female", "male" is more
descriptive than 1, 2. Which one is ““male”“? You wouldn’t be able to
tell just from the integer data. Factors, on the other hand, have this
information built in. It is particularly helpful when there are many
levels (like the species names in our example dataset).
Try changing the columns taxa and genus in
the surveys data frame into a factor.
Using the functions you’ve learned, see if you can find out: how many
rabbits were observed? How many different genera are in the
genus column?
# change taxa to a factor
surveys$taxa <- factor(surveys$taxa)
# change genus to a factor
surveys$genus <- factor(surveys$genus)
# call summary
summary(surveys)
# there are 75 rabbits in the taxa column
# cannot count total number of genera in summary output
nlevels(surveys$genus)
# there are 26 unique genera
If you need to convert a factor to a character vector, you use
as.character(x).
as.character(sex)
## [1] "male" "female" "female" "male"
In some cases, you may have to convert factors where the levels
appear as numbers (such as concentration levels or years) to a numeric
vector. For instance, in one part of your analysis the years might need
to be encoded as factors (e.g., comparing average weights
across years) but in another part of your analysis they may need to be
stored as numeric values (e.g., doing math operations on the
years). This conversion from factor to numeric is a little trickier and
can introduce errors if not done properly. The as.numeric()
function returns the index values of the factor, not its
levels, so it will result in an entirely new (and unwanted in this case)
set of numbers. One method to avoid this is to convert factors to
characters, and then to numbers.
year_fct <- factor(c(1990, 1983, 1977, 1998, 1990))
as.numeric(year_fct) # Wrong! And there is no warning...
as.numeric(as.character(year_fct)) # Works
Another method is to use the levels() function. This
approach accomplishes three important steps:
levels(year_fct)as.numeric(levels(year_fct))year_fct inside square bracketsas.numeric(levels(year_fct))[year_fct]
When your data are stored as a factor, you can use the
plot() function to get a quick glance at the number of
observations represented by each factor level. Let’s look at the number
of males and females captured over the course of the experiment:
## bar plot of the number of females and males captured during the experiment:
plot(surveys$sex)
However, as we saw when we used summary(surveys$sex),
there are about 1700 individuals for which the sex information hasn’t
been recorded. To show them in the plot, we can turn the missing values
into a factor level with the addNA() function. We will also
have to give the new factor level a label. We are going to work with a
copy of the sex column, so we’re not modifying the working
copy of the data frame:
# create new object with just the sex column
sex <- surveys$sex
# check number of levels
levels(sex)
## [1] "F" "M"
# include missing data as a level
sex <- addNA(sex)
# check number of levels
levels(sex)
## [1] "F" "M" NA
# view counts for each factor
summary(sex)
## F M <NA>
## 15690 17348 1748
# change the name of level 3 to "undetermined"
levels(sex)[3] <- "undetermined"
# check levels again
levels(sex)
## [1] "F" "M" "undetermined"
# view counts for each factor
summary(sex)
## F M undetermined
## 15690 17348 1748
Now we can plot the data again using plot(sex).
Note that to alter the variable in the data frame, you would simply
substitute surveys$sex, or the name of the column in the
data frame, for sex in the code we’ve just written.
Try renaming “F” and “M” to “female” and “male” respectively.
Now that we have renamed the factor level to “undetermined”, can you
recreate the barplot such that “undetermined” is first (before
“female”)?
# view levels
levels(sex)
# change name of first two levels of object sex
levels(sex)[1:2] <- c("female", "male")
# reorder levels
sex <- factor(sex, levels = c("undetermined", "female", "male"))
# create plot with changes to factor
plot(sex)
The automatic conversion of data type is sometimes a blessing, sometimes an annoyance. Be aware that it exists, learn the rules, and double check that data you import in R are of the correct type within your data frame. If not, use it to your advantage to detect mistakes that might have been introduced during data entry (for instance, a letter in a column that should only contain numbers).
A common issue that new (and experienced!) R users have is converting
date and time information into a variable that is suitable for analyses.
One way to store date information is to store each component of the date
in a separate column. Using str(), we can confirm that our
data frame does indeed have a separate column for day, month, and year,
and that each of these columns contains integer values.
str(surveys)
We are going to use the ymd() function from the package
lubridate. lubridate gets installed as part as
the tidyverse installation. When you load the tidyverse
(library(tidyverse)), the core packages (the packages used
in most data analyses) get loaded. lubridate however does
not belong to the core tidyverse, so you have to load it explicitly with
library(lubridate).
Start by loading the required package:
library(lubridate)
The lubridate package has many useful functions for
working with dates. These can help you extract dates from different
string representations, convert between timezones, calculate time
differences and more. You can find an overview of them in the lubridate
cheat sheet.
Here we will use the function ymd(), which takes a
vector representing year, month, and day, and converts it to a
Date vector. Date is a class of data
recognized by R as being a date and can be manipulated as such. The
argument that the function requires is flexible, but, as a best
practice, is a character vector formatted as
“YYYY-MM-DD”.
Let’s create a date object and inspect the structure:
my_date <- ymd("2015-01-01")
str(my_date)
If we use paste() to enter the year, month, and day
separately, using “-” as a separator, we get the same
result:
my_date <- ymd(paste("2015", "1", "1", sep = "-"))
str(my_date)
Remember our date in surveys is stored separately as year, month, day. So we can create a character vector from these columns using paste, just as we did for the single date above:
paste(surveys$year, surveys$month, surveys$day, sep = "-")
If you run this code, you will output a vector that has every date in
the data frame formatted in YYYY-MM-DD format…but they are still
characters, not dates. We can pass this character vector as an argument
to the ymd() function using the following code:
ymd(paste(surveys$year, surveys$month, surveys$day, sep = "-"))
## Warning: 129 failed to parse.
There is a warning telling us that some dates could not be parsed
(understood) by the ymd() function. For these dates, the
function has returned NA, which means they are treated as
missing values. We will deal with this problem later, but first we add
the resulting Date vector to the surveys data
frame as a new column called date:
surveys$date <- ymd(paste(surveys$year, surveys$month, surveys$day, sep = "-"))
## Warning: 129 failed to parse.
str(surveys) # notice the new column, with "Date" as the class
Let’s make sure everything worked correctly. One way to inspect the
new column is to use summary():
summary(surveys$date)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## "1977-07-16" "1984-03-12" "1990-07-22" "1990-12-15" "1997-07-29" "2002-12-31"
## NA's
## "129"
Let’s investigate why some dates could not be parsed.
We can use the functions we saw previously to deal with missing data
to identify the rows in our data frame that are failing. If we combine
them with what we learned about subsetting data frames earlier, we can
extract the columns
"year","month","day" from the
records that have NA in our new column date.
We will also use head() so we don’t clutter the output:
# create new subset data frame called missing_dates
# Call all rows for which surveys$date is missing, and call the three date columns
missing_dates <- surveys[is.na(surveys$date), c("year", "month", "day")]
# look at the first few rows
head(missing_dates)
## # A tibble: 6 × 3
## year month day
## <dbl> <dbl> <dbl>
## 1 2000 9 31
## 2 2000 4 31
## 3 2000 4 31
## 4 2000 4 31
## 5 2000 4 31
## 6 2000 9 31
Why did these dates fail to parse? If you had to use these data for your analyses, how would you deal with this situation?
The answer is because the dates provided as input for the
ymd() function do not actually exist. If we refer to the
output we got above, September and April only have 30 days, not 31 days
as it is specified in our dataset.
There are several ways you could deal with situation:
Regardless of the option you choose, it is important that you document the error and the corrections (if any) that you apply to your data. We’ll discuss data management, and how to keep records that would allow you to correct this kind of error, later in the course. As you can see here, minor errors in data entry can result in excluding 100s of observations, which is something we like to avoid!
Use the questions below to test your understanding of the concepts we covered in this unit. When you are finished, enter your answers in the online quiz. You can take the quiz as many times as you like! So if you miss a question, you can review that section of the workshop and try again.
read_csv() function in the tidyverse package
assumes that columns are separated by
data.data[ , 1] R will return
data.data[-50 , ] R will return
surveys?
sex column from the object surveys? (More than
one answer may be true.)
animal_data <- data.frame(
animal = c(dog, cat, sea cucumber, sea urchin),
feel = c("furry", "squishy", "spiny"),
weight = c(45, 8 1.1, 0.8)
)
Ernest, Morgan; Brown, James; Valone, Thomas; White, Ethan P. (2018): Portal Project Teaching Database. figshare. Dataset. https://doi.org/10.6084/m9.figshare.1314459.v10
Kamvar ZN (2022). “datacarpentry/R-ecology-lesson: Data Carpentry: Data Analysis and Visualization in R for Ecologists, June 2019.” doi:10.5281/zenodo.3264888, https://datacarpentry.org/R-ecology-lesson/.