Learning Objectives

  • Load external data into a data frame.
  • Describe what a data frame is.
  • Summarize the contents of a data frame.
  • Use indexing to subset specific portions of data frames.
  • Describe what a factor is.
  • Convert between strings and factors.
  • Reorder and rename factors.
  • Change how character strings are handled in a data frame.

To begin to manipulate data in R, we are first going to read in the metadata from last week’s workshop.

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 see the contents of the data frame by typing its name: metadata.

Let’s check the top (the first 6 lines) of this data frame using the function head():

#>         SampleID MouseID Time_days   Treatment
#> 1 MOUSE.G11.Day1     G11         1 Before_Diet
#> 2 MOUSE.G11.Day3     G11         3 Before_Diet
#> 3 MOUSE.G11.Day7     G11         7 Before_Diet
#> 4 MOUSE.G12.Day1     G12         1 Before_Diet
#> 5 MOUSE.G12.Day3     G12         3 Before_Diet
#> 6 MOUSE.G12.Day7     G12         7 Before_Diet

Note

The header argument has to be set to TRUE to be able to read the headers as by default read.table() has the header argument set to FALSE.

It is also good practice to develop the habits of looking at and record some parameters of your data files. For instance, the character encoding, control characters used for line ending, date format (if the date is not splitted into three variables), and the presence of unexpected newlines are important characteristics of your data files. Those parameters will ease up the import step of your data in R.

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 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 when inspecting the structure of a data frame with the function str():

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(metadata) - 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(metadata) - returns the number of rows
    • ncol(metadata) - returns the number of columns
  • Content:
    • head(metadata) - shows the first 6 rows
    • tail(metadata) - shows the last 6 rows
  • Names:
    • names(metadata) - returns the column names (synonym of colnames() for data.frame objects)
    • rownames(metadata) - returns the row names
  • Summary:
    • str(metadata) - structure of the object and information about the class, length and content of 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(metadata), can you answer the following questions?

  • What is the class of the object metadata?
  • How many rows and how many columns are in this object?
  • How many unique mice are in our dataset?

Answer

#> 'data.frame':  18 obs. of  4 variables:
#>  $ SampleID : Factor w/ 18 levels "MOUSE.G11.Day1",..: 1 2 3 4 5 6 7 8 9 10 ...
#>  $ MouseID  : Factor w/ 6 levels "G11","G12","G21",..: 1 1 1 2 2 2 3 3 3 4 ...
#>  $ Time_days: int  1 3 7 1 3 7 1 3 7 1 ...
#>  $ Treatment: Factor w/ 2 levels "After_Diet","Before_Diet": 2 2 2 2 2 2 2 2 2 1 ...

Indexing and subsetting data frames

Our 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.

: 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 indices of a data frame using the “-” sign:

Data frames can be subset by calling indices (as shown previously), but also by calling their column names directly:

In RStudio, you can use the autocompletion feature to get the full and correct names of the columns.

Factors

When we did str(metadata) we saw that the column Time_days consists of integers. The columns SampleID, MouseID, Treatment however, are of a special class called factor. Factors can be very useful and contribute to making R particularly well suited to working with data, however, they can also be confusing. So we are going to spend a little time introducing them.

Factors represent categorical data. They 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.

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:

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():

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:

#> [1] male   female female male  
#> Levels: female male
#> [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).

Converting factors

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

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. 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.

Another method is to use the levels() function. Compare:

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

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

Using stringsAsFactors=FALSE

By default, when building or importing a data frame, the columns that contain characters (i.e. text) are coerced (= converted) into factors. 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 is preferable to set stringsAsFactors = FALSE when importing data and to convert as a factor only the columns that require this data type.

Challenge

  1. We have seen how data frames are created when using 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!

  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 when creating the data frame?
    • What would you need to change to ensure that each column had the accurate data type?

    Answer

    • missing quotations around the names of the animals
    • missing one entry in the feel column (probably for one of the furry animals)
    • missing one comma in the weight column
    • country, climate, temperature, and northern_hemisphere are factors; has_kangaroo is numeric
    • using stringsAsFactors = FALSE would have made character vectors instead of factors
    • removing the quotes in temperature and northern_hemisphere and replacing 1 by TRUE in the has_kangaroo column would give what was probably intended

The automatic conversion of data type is controversial. 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).

Learn more in this RStudio tutorial

In BIG NEWS, stringsAsFactors will be FALSE by default in R 4.0.0 (released on 4/24/2020!).

Page built on: 📆 2020-04-23 ‒ 🕢 11:21:36


Data Carpentry, 2014-2019.

License. Contributing.

Questions? Feedback? Please file an issue on GitHub.
On Twitter: @datacarpentry

If this lesson is useful to you, consider subscribing to our newsletter or making a donation to support the work of The Carpentries.