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.
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()
:
data.frame
ObjectsWe 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(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 rowsncol(metadata)
- returns the number of columnshead(metadata)
- shows the first 6 rowstail(metadata)
- shows the last 6 rowsnames(metadata)
- returns the column names (synonym of colnames()
for data.frame
objects)rownames(metadata)
- returns the row namesstr(metadata)
- structure of the object and information about the class, length and content of each columnNote: 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 ...
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.
# first element in the first column of the data frame (as a vector)
metadata[1, 1]
# first element in the 6th column (as a vector)
metadata[1, 3]
# first column of the data frame (as a vector)
metadata[, 1]
# first column of the data frame (as a data.frame)
metadata[1]
# first three elements in the 7th column (as a vector)
metadata[1:3, 4]
# the 3rd row of the data frame (as a data.frame)
metadata[3, ]
# equivalent to head_metadata <- head(metadata)
head_metadata <- metadata[1:6, ]
:
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:
metadata[, -1] # The whole data frame, except the first column
metadata[-c(7:nrow(metadata)), ] # Equivalent to head(metadata)
Data frames can be subset by calling indices (as shown previously), but also by calling their column names directly:
metadata["SampleID"] # Result is a data.frame
metadata[, "SampleID"] # Result is a vector
metadata[["SampleID"]] # Result is a vector
metadata$SampleID # Result is a vector
In RStudio, you can use the autocompletion feature to get the full and correct names of the columns.
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).
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:
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...
as.numeric(levels(year_fct))[year_fct] # The recommended way.
Notice that in the levels()
approach, three important steps occur:
levels(year_fct)
as.numeric(levels(year_fct))
year_fct
inside the square bracketsstringsAsFactors=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.
## Compare the difference between our data read as `factor` vs `character`.
metadata <- read.table("metadata.tsv", header = TRUE, stringsAsFactors = TRUE)
str(metadata)
metadata <- read.table("metadata.tsv", header = TRUE, stringsAsFactors = FALSE)
str(metadata)
## Convert the column "Treatment" into a factor
metadata$Treatment <- factor(metadata$Treatment)
levels(metadata$Treatment)
Challenge
We have seen how data frames are created when using
read.csv()
, but they can also be created by hand with thedata.frame()
function. There are a few mistakes in this hand-crafteddata.frame
. Can you spot and fix them? Don’t hesitate to experiment!- 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?
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) )
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
columncountry
,climate
,temperature
, andnorthern_hemisphere
are factors;has_kangaroo
is numeric- using
stringsAsFactors = FALSE
would have made character vectors instead of factors- removing the quotes in
temperature
andnorthern_hemisphere
and replacing 1 by TRUE in thehas_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.
Questions? Feedback?
Please file
an issue on GitHub.
On Twitter: @datacarpentry
If this lesson is useful to you, consider