Learning Objectives

  • Describe what a data frame is.
  • Load external data from a .csv file into a data frame in R.
  • Summarize the contents of a data frame in R.
  • Manipulate categorical data in R.
  • Change how character strings are handled in a data frame.
  • Format dates in R

Presentation of the iDigBio data

We are working with data about specimens from 4 genera in the order rodentia. These specimens are housed in natural history collections in the lower 48 states are are aggregated and served through iDigBio, the US’s natural history museum digitization hub.

The data set was retrieved from the iDigBio data portal and the file used for teaching here has been simplified by removing many columns of detailed information. These specimens are from many different collections at institutions like the Museum of Vertebrate Zoology at Berkeley and the Ohio State Museum of Natural History.

Column names are Dawin Core terms which have standardized definitions that you can read about in the specification. There are a few columns that iDigBio has added that are not standard and they are noted. Below is a brief description of the information in this data set:

Column Description
id A globally unique identifier for the record
institutionCode An identifier for the institution
collectionCode Identifies the collection at an institution
catalogNumber Legacy identifier of the speciemen
recordedBy Who collected it
countryCode 3 letter abbreviation of counrty
stateProvince State where speciemen was collected
county County where speciment was collected
locality Textual description of collection location
decimalLatitude Latitute and longitude
decimalLongitude Latitute and longitude
eventDate When the specimen was collected
year When the specimen was collected
month When the specimen was collected
day When the specimen was collected
genus Genus
specificEpithet Species
scientificName Full textual taxanomic name
weight Weight in grams extracted from text
length Length in mm extracted from text
sex Sex extracted from text

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 into memory the content of the CSV file as an object of class data.frame.

To download the data into the data/ subdirectory, run the following:

FIXME: Data path

download.file("https://ndownloader.figshare.com/files/9582724",
              "data/idigbio_rodents.csv")

You are now ready to load the data:

specimens <- read.csv("data/idigbio_rodents.csv")

This statement doesn’t produce any output because, as you might recall, assignments don’t display anything. If we want to check that our data has been loaded, we can print the variable’s value: specimens.

Wow… that was a lot of output. At least it means the data loaded properly. Let’s check the top (the first 6 lines) of this data frame using the function head():

head(specimens)
#>                                   uuid institutionCode   collectionCode
#> 1 060380ea-7b06-474e-8d2e-b6e4a8c21e1a             mvz mammal specimens
#> 2 0fb17a79-a8ce-45b6-b57a-2f640e8cccb6             mvz mammal specimens
#> 3 1a69c8ad-0ac3-4612-9dc0-6867e8b9a218             mvz mammal specimens
#> 4 1a9932b4-beab-4472-bec1-a7e68c4b9e6e             mvz mammal specimens
#> 5 1f3b8aea-fbae-46d1-91c8-274924b40c9f             mvz mammal specimens
#> 6 203f0531-9b46-403f-ac09-3acab5be977c             uam mammal specimens
#>   catalogNumber                                                recordedBy
#> 1        219088 collector(s): ana lilia trujano álvarez, eric ghilarducci
#> 2        233524                     collector(s): william z. lidicker jr.
#> 3        234346                     collector(s): william z. lidicker jr.
#> 4        233951                     collector(s): william z. lidicker jr.
#> 5        235290                     collector(s): william z. lidicker jr.
#> 6         85106    collector(s): tom manning; preparator(s): amber baxter
#>   countryCode stateProvince              county decimalLatitude
#> 1         usa    california contra costa county        37.76095
#> 2         usa    california contra costa county        37.89996
#> 3         usa    california contra costa county        37.89996
#> 4         usa    california contra costa county        37.89996
#> 5         usa    california contra costa county        37.89996
#> 6         usa        oregon      douglas county        43.27512
#>   decimalLongitude                     eventDate year month day    genus
#> 1        -121.8866 2005-11-22T19:00:00.000-05:00 2005    11  22 microtus
#> 2        -122.3617 1959-06-20T20:00:00.000-04:00 1959     6  20 microtus
#> 3        -122.3617 1962-11-21T19:00:00.000-05:00 1962    11  21 microtus
#> 4        -122.3617 1960-07-30T20:00:00.000-04:00 1960     7  30 microtus
#> 5        -122.3617 1964-07-03T20:00:00.000-04:00 1964     7   3 microtus
#> 6        -122.7911 1996-10-22T20:00:00.000-04:00 1996    10  22   myodes
#>   specificEpithet                     scientificName weight length    sex
#> 1    californicus microtus californicus californicus   30.5    165   male
#> 2    californicus microtus californicus californicus   22.0    143 female
#> 3    californicus microtus californicus californicus   49.0    187   male
#> 4    californicus microtus californicus californicus   33.0    169 female
#> 5    californicus microtus californicus californicus   29.0    159 female
#> 6    californicus                myodes californicus   23.5    141 female

What are data frames?

Data frames are the de facto data structure for most tabular data, and what we use for statistics and plotting.

A data frame can be created by hand, but most commonly they are generated by the functions read.csv() or read.table(); 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 the column are vectors, they all contain the same type of data (e.g., characters, integers, factors). For example, here is a figure depicting a data frame comprising of a numeric, a character and a logical vector.

We can see this when inspecting the structure of a data frame with the function str():

str(specimens)

Inspecting data.frame Objects

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!

  • Size:
    • dim(specimens) - 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(specimens) - returns the number of rows
    • ncol(specimens) - returns the number of columns
  • Content:
    • head(specimens) - shows the first 6 rows
    • tail(specimens) - shows the last 6 rows
  • Names:
    • names(specimens) - returns the column names (synonym of colnames() for data.frame objects)
    • rownames(specimens) - returns the row names
  • Summary:
    • str(specimens) - structure of the object and information about the class, length and content of each column
    • summary(specimens) - summary statistics for each column

Note: most of these functions are “generic”, they can be used on other types of objects besides data.frame.

Challenge

Based on the output of str(specimens), can you answer the following questions?

  • What is the class of the object specimens?
  • How many rows and how many columns are in this object?
  • How many genera are represented by these specimens?

Indexing and subsetting data frames

Our survey data frame has rows and columns (it has 2 dimensions), 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. However, note that different ways of specifying these coordinates lead to results with different classes.

specimens[1, 1]   # first element in the first column of the data frame (as a vector)
specimens[1, 6]   # first element in the 6th column (as a vector)
specimens[, 1]    # first column in the data frame (as a vector)
specimens[1]      # first column in the data frame (as a data.frame)
specimens[1:3, 7] # first three elements in the 7th column (as a vector)
specimens[3, ]    # the 3rd element for all columns (as a data.frame)
head_specimens <- specimens[1:6, ] # equivalent to head(specimens)

: is a special function that creates numeric vectors of integers in increasing or decreasing order, test 1:10 and 10:1 for instance.

You can also exclude certain parts of a data frame using the “-” sign:

specimens[,-1]          # The whole data frame, except the first column
specimens[-c(7:10767),] # Equivalent to head(specimens)

As well as using numeric values to subset a data.frame (or matrix), columns can be called by name, using one of the four following notations:

specimens["genus"]       # Result is a data.frame
specimens[, "genus"]     # Result is a vector
specimens[["genus"]]     # Result is a vector
specimens$genus          # Result is a vector

For our purposes, the last three notations are equivalent. RStudio knows about the columns in your data frame, so you can take advantage of the autocompletion feature to get the full and correct column name.

Challenge

  1. Create a data.frame (specimens_200) containing only the observations from row 200 of the specimens dataset.

  2. Notice how nrow() gave you the number of rows in a data.frame?

    • Use that number to pull out just that last row in the data frame.
    • Compare that with what you see as the last row using tail() to make sure it’s meeting expectations.
    • Pull out that last row using nrow() instead of the row number.
    • Create a new data frame object (specimens_last) from that last row.
  3. Use nrow() to extract the row that is in the middle of the data frame. Store the content of this row in an object named specimens_middle.

  4. Combine nrow() with the - notation above to reproduce the behavior of head(specimens) keeping just the first through 6th rows of the specimens dataset.

Factors

When we did str(specimens) we saw that several of the columns consist of integers, however, the columns genus, county, catalogNumber, … are of a special class called a factor. Factors are very useful and are actually something that make R particularly well suited to working with data, so we’re going to spend a little time introducing them.

Factors are used to represent categorical data. Factors can be ordered or unordered, and understanding them is necessary for statistical analysis and for plotting.

Factors are stored as integers, and have labels (text) associated with these unique integers. While factors look (and often behave) like character vectors, they are actually integers under the hood, and you need to be careful when treating them like strings.

Once created, factors can only contain a pre-defined set of values, known as levels. 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 "amara" and 2 to the level "omus" (because a comes before o, even though the first element in this vector is "omus"). You can check this by using the function levels(), and check 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 re-ordering
#> [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 sex in our example dataset).

Converting factors

If you need to convert a factor to a character vector, you use as.character(x).

as.character(sex)

Converting factors where the levels appear as numbers (such as concentration levels, or years) to a numeric vector is a little trickier. One method is to convert factors to characters and then numbers. Another method is to use the levels() function. Compare:

f <- factor(c(1990, 1983, 1977, 1998, 1990))
as.numeric(f)               # wrong! and there is no warning...
as.numeric(as.character(f)) # works...
as.numeric(levels(f))[f]    # The recommended way.

Notice that in the levels() approach, three important steps occur:

  • We obtain all the factor levels using levels(f)
  • We convert these levels to numeric values using as.numeric(levels(f))
  • We then access these numeric values using the underlying integers of the vector f inside the square brackets

Renaming factors

When your data is 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(specimens$sex)

In addition to males and females, there are about 1500 individuals for which the sex information hasn’t been recorded. Additionally, for these individuals, there is no label to indicate that the information is missing. Let’s rename this label to something more meaningful. Before doing that, we’re going to pull out the data on sex and work with that data, so we’re not modifying the working copy of the data frame:

sex <- specimens$sex
head(sex)
#> [1] male   female male   female female female
#> Levels:  female male
levels(sex)
#> [1] ""       "female" "male"
levels(sex)[1] <- "missing"
levels(sex)
#> [1] "missing" "female"  "male"
head(sex)
#> [1] male   female male   female female female
#> Levels: missing female male

Challenge

  • Rename “female” and “male” to “F” and “M” respectively.
  • Now that we have renamed the factor level to “missing”, can you recreate the barplot such that “missing” is last (after “male”)?

Using stringsAsFactors=FALSE

By default, when building or importing a data frame, the columns that contain characters (i.e., text) are coerced (=converted) into the factor data type. Depending on what you want to do with the data, you may want to keep these columns as character. To do so, read.csv() and read.table() have an argument called stringsAsFactors which can be set to FALSE.

In most cases, it’s preferable to set stringsAsFactors = FALSE when importing your data, and converting as a factor only the columns that require this data type.

Compare the output of str(specimens) when setting stringsAsFactors = TRUE (default) and stringsAsFactors = FALSE:

## Compare the difference between when the data are being read as
## `factor`, and when they are being read as `character`.
specimens <- read.csv("data/idigbio_rodents.csv", stringsAsFactors = TRUE)
str(specimens)
specimens <- read.csv("data/idigbio_rodents.csv", stringsAsFactors = FALSE)
str(specimens)
## Convert the column "genus" into a factor
specimens$genus <- factor(specimens$genus)

Challenge

  1. We have seen how data frames are created when using the read.csv(), but they can also be created by hand with the data.frame() function. There are a few mistakes in this hand-crafted data.frame, can you spot and fix them? Don’t hesitate to experiment!

    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))
  2. Can you predict the class for each of the columns in the following example? Check your guesses using str(country_climate):
    • Are they what you expected? Why? Why not?
    • What would have been different if we had added stringsAsFactors = FALSE to this call?
    • What would you need to change to ensure that each column had the accurate data type?
    country_climate <- data.frame(
           country=c("Canada", "Panama", "South Africa", "Australia"),
           climate=c("cold", "hot", "temperate", "hot/temperate"),
           temperature=c(10, 30, 18, "15"),
           northern_hemisphere=c(TRUE, TRUE, FALSE, "FALSE"),
           has_kangaroo=c(FALSE, FALSE, FALSE, 1)
           )

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 (a letter in a column that should only contain numbers for instance).

Formatting Dates

One of the most common issues that new (and experienced!) R users have is converting date and time information into a variable that is appropriate and usable during analyses. As a reminder from earlier in this lesson, the best practice for dealing with date data is to ensure that each component of your date is stored as a separate variable. Using str(), We can confirm that our data frame has a separate column for day, month, and year, and each contains integer values.

str(specimens)

We’re going to be using the ymd() function from the package lubridate. This function is designed to take a vector representing year, month, and day and convert that information to a POSIXct vector. POSIXct is a class of data recognized by R as being a date or date and time. The argument that the function requires is relatively flexible, but, as a best practice, is a character vector formatted as “YYYY-MM-DD”.

Start by loading the required package:

library(lubridate)

Create a character vector from the year, month, and day columns of specimens using paste():

paste(specimens$year, specimens$month, specimens$day, sep="-")
# sep indicates the character to use to separate each component

This character vector can be used as the argument for ymd():

ymd(paste(specimens$year, specimens$month, specimens$day, sep="-"))

The resulting POSIXct vector can be added to specimens as a new column called date:

specimens$date <- ymd(paste(specimens$year, specimens$month, specimens$day, sep="-"))

str(specimens) # notice the new column, with 'date' as the class

Page build on: 2017-10-25 10:36:17


Data Carpentry, 2017. License. Contributing.
Questions? Feedback? Please file an issue on GitHub.
On Twitter: @datacarpentry