Starting with data
Overview
Teaching: min
Exercises: minQuestions
Objectives
Load external data from a .csv file 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.
Format dates.
Presentation of the ADNI Dataset
The data we will be using today is from the Alzheimer’s Disease Neuroimaging Initiative (ADNI).
ADNI is a global research study that actively supports the investigation and development of treatments that slow or stop the progression of AD. In this multisite longitudinal study, researchers at 63 sites in the US and Canada track the progression of AD in the human brain with clinical, imaging, genetic and biospecimen biomarkers through the process of normal aging, early mild cognitive impairment (EMCI), and late mild cognitive impairment (LMCI) to dementia or AD. The overall goal of ADNI is to validate biomarkers for use in Alzheimer’s disease clinical treatment trials. The dataset is stored as a comma separated value (CSV) file.
Each row holds information for a single patient visit, and the columns represent patient attributes.
Column | Description |
---|---|
PTID | unique patient identifier |
AGE_mod | a modified patient age for deidentification |
PTGENDER | the patient’s gender |
PTMARRY | the patient’s marital status |
PTEDUCATE | the patient’s educational status |
DX | the patient’s diagnosis |
SITE | the study site the patient was seen at |
EXAMDATE_mod | the date the patient was seen |
WholeBrain | the volume of the patient’s brain at a given visit |
WholeBrain_bl | the volume of the patient’s brain at the baseline visit |
Hippocampus | the volume of the patient’s hippocampus at a given visit |
APOE4 | the number of risk alleles the pateient has in the APOE4 gene |
TAU_mod | Level of the TAU biomarker in cerebrospinal fluid |
For a full data inventory, see (http://adni.loni.usc.edu/data-samples/adni-data-inventory/)
We will use read.csv()
to load into memory the content of the CSV file as an object of class data.frame
.
You should have downloaded the data for this lesson at the beginning of the day. It should be in a folder called “data”.
You are now ready to load the data:
adni_r <- read.csv("data/ADNIMERGE.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 see the contents of the data frame by typing its name: adni_r
.
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(adni_r)
PTID VISCODE AGE_mod PTGENDER PTMARRY PTEDUCAT DX SITE
1 011_S_0002 bl 74.3 Male Married 16 CN 11
2 011_S_0003 bl 81.3 Male Married 18 Dementia 11
3 011_S_0003 m06 81.3 Male Married 18 Dementia 11
4 011_S_0003 m12 81.3 Male Married 18 Dementia 11
5 011_S_0003 m24 81.3 Male Married 18 Dementia 11
6 022_S_0004 bl 67.5 Male Married 10 MCI 22
EXAMDATE_mod WholeBrain WholeBrain_bl Hippocampus APOE4 TAU_mod
1 2005-08-18 1229740 1229740 8336 0 -4.0
2 2005-10-11 1129830 1129830 5319 1 239.7
3 2006-03-11 1100060 1129830 5446 1 -4.0
4 2006-09-29 1095640 1129830 5157 1 251.7
5 2007-09-06 1088560 1129830 5139 1 -4.0
6 2005-11-10 1154980 1154980 6869 0 153.1
## Try also
View(adni_r)
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 exactly likeread.csv
but uses different parameters for the decimal and the field separators. If you are working with another format, they can be both specified by the user. Check out the help forread.csv()
by typing?read.csv
to learn more. There is also theread.delim()
for in tab separated data files. It is important to note that all of these functions are actually wrapper functions for the mainread.table()
function with different arguments. As such, the ANDI data above could have also been loaded by usingread.table()
with the separation argument as,
. The code is as follows:adni_r <- read.table(file="data/ADNIMERGE.csv", sep=",", header=TRUE)
. The header argument has to be set to TRUE to be able to read the headers as by defaultread.table()
has the header argument set to FALSE.
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()
:
str(adni_r)
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(adni_r)
- 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(adni_r)
- returns the number of rowsncol(adni_r)
- returns the number of columns
- Content:
head(adni_r)
- shows the first 6 rowstail(adni_r)
- shows the last 6 rows
- Names:
names(adni_r)
- returns the column names (synonym ofcolnames()
fordata.frame
objects)rownames(adni_r)
- returns the row names
- Summary:
str(adni_r)
- structure of the object and information about the class, length and content of each columnsummary(adni_r)
- 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(adni_r)
, can you answer the following questions?
- What is the class of the object
adni_r
?- How many rows and how many columns are in this object?
- How many types of diagnoses have been observed during this study?
str(adni_r)
'data.frame': 13900 obs. of 14 variables: $ PTID : Factor w/ 2152 levels "002_S_0295","002_S_0413",..: 241 242 242 242 242 531 531 531 531 531 ... $ VISCODE : Factor w/ 26 levels "bl","m03","m06",..: 1 1 3 7 14 1 3 7 13 16 ... $ AGE_mod : num 74.3 81.3 81.3 81.3 81.3 67.5 67.5 67.5 67.5 67.5 ... $ PTGENDER : Factor w/ 2 levels "Female","Male": 2 2 2 2 2 2 2 2 2 2 ... $ PTMARRY : Factor w/ 5 levels "Divorced","Married",..: 2 2 2 2 2 2 2 2 2 2 ... $ PTEDUCAT : int 16 18 18 18 18 10 10 10 10 10 ... $ DX : Factor w/ 4 levels "-4","CN","Dementia",..: 2 3 3 3 3 4 4 4 4 4 ... $ SITE : int 11 11 11 11 11 22 22 22 22 22 ... $ EXAMDATE_mod : Factor w/ 4213 levels "2005-08-18","2005-09-03",..: 1 4 85 258 595 13 108 284 499 1006 ... $ WholeBrain : int 1229740 1129830 1100060 1095640 1088560 1154980 1116280 1117390 1095210 1085350 ... $ WholeBrain_bl: int 1229740 1129830 1129830 1129830 1129830 1154980 1154980 1154980 1154980 1154980 ... $ Hippocampus : int 8336 5319 5446 5157 5139 6869 6439 6451 6373 6213 ... $ APOE4 : int 0 1 1 1 1 0 0 0 0 0 ... $ TAU_mod : num -4 240 -4 252 -4 ...
Solution
- class: data frame
- how many rows: 13,900, how many columns: 112
- how many types of diagnoses (DX): 4
Indexing and subsetting data frames
Our ADNI 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)
adni_r[1, 1]
# first element in the 6th column (as a vector)
adni_r[1, 6]
# first column of the data frame (as a vector)
adni_r[, 1]
# first column of the data frame (as a data.frame)
adni_r[1]
# first three elements in the 7th column (as a vector)
adni_r[1:3, 7]
# the 3rd row of the data frame (as a data.frame)
adni_r[3, ]
# equivalent to head_adni <- head(adni_r)
head_adni <- adni_r[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:
adni_r[, -1] # The whole data frame, except the first column
adni_r[-c(7:34786), ] # Equivalent to head(adni_r)
Data frames can be subset by calling indices (as shown previously), but also by calling their column names directly:
adni_r["DX"] # Result is a data.frame
adni_r[, "DX"] # Result is a vector
adni_r[["DX"]] # Result is a vector
adni_r$DX # Result is a vector
In RStudio, you can use the autocompletion feature to get the full and correct names of the columns.
Challenge
Create a
data.frame
(adni_200
) containing only the data in row 200 of theadni_r
dataset.Notice how
nrow()
gave you the number of rows in adata.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 (
adni_last
) from that last row.Use
nrow()
to extract the row that is in the middle of the data frame. Store the content of this row in an object namedadni_middle
.Combine
nrow()
with the-
notation above to reproduce the behavior ofhead(adni_r)
, keeping just the first through 6th rows of the adni dataset.Solution
# 1. adni <- adni[200, ]
Error in eval(expr, envir, enclos): object 'adni' not found
# 2. # Saving `n_rows` to improve readability and reduce duplication n_rows <- nrow(adni)
Error in nrow(adni): object 'adni' not found
adni_last <- adni[n_rows, ]
Error in eval(expr, envir, enclos): object 'adni' not found
# 3. adni_middle <- adni[n_rows / 2, ]
Error in eval(expr, envir, enclos): object 'adni' not found
# 4. adni_head <- adni[-(7:n_rows), ]
Error in eval(expr, envir, enclos): object 'adni' not found
Factors
When we did str(adni_r)
we saw that several of the columns consist of
integers. The columns PTID
, PTMARRY
, DX
, PTGENDER
, … however, are
of a special class 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.
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:
gender <- 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(gender)
nlevels(gender)
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 gender
vector would be:
gender # current order
[1] Male Female Female Male
Levels: Female Male
gender <- factor(gender, levels = c("Male", "Female"))
gender # 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 species names in our example dataset).
Converting factors
If you need to convert a factor to a character vector, you use
as.character(x)
.
as.character(gender)
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 ages between genders) 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:
- 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
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 men and women studied:
plot(adni_r$PTGENDER)
You may need to rename the levels of your factors. Here’s an example of how to rename the “Female” factor to “Female”
gender <- adni_r$PTGENDER
head(gender)
[1] Male Male Male Male Male Male
Levels: Female Male
levels(gender)
[1] "Female" "Male"
levels(gender)[1] <- "female"
levels(gender)
[1] "female" "Male"
head(gender)
[1] Male Male Male Male Male Male
Levels: female Male
Challenge
- Rename “female” and “male” to “F” and “M” respectively.
- Can you recreate the barplot such that “M” is before “F”?
Solution
levels(gender) <- c("F", "M") gender <- factor(gender, levels = c( "M", "F")) plot(gender)
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.
## Compare the difference between our data read as `factor` vs `character`.
adni_r <- read.csv("data/ADNIMERGE.csv", stringsAsFactors = TRUE)
str(adni_r)
adni_r <- read.csv("data/ADNIMERGE.csv", stringsAsFactors = FALSE)
str(adni_r)
## Convert the column "plot_type" into a factor
adni_r$SITE <- factor(adni_r$SITE)
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!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) )
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) )
Solution
1.
- 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
column2.
country
,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 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).
Learn more in this RStudio tutorial
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 that each contains
integer values.
str(adni_r)
We are going to use the ymd()
function from the package lubridate
(which belongs to the tidyverse
; learn more here). . 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)
ymd()
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)
Now let’s paste the year, month, and day separately - we get the same result:
# sep indicates the character to use to separate each component
my_date <- ymd(paste("2015", "1", "1", sep = "-"))
str(my_date)
Now we apply this function to the ADNI dataset. Change the EXAMDATE_mod
column to character:
adni_r$EXAMDATE_mod<-as.character(adni_r$EXAMDATE_mod)
This character vector can be used as the argument for ymd()
:
adni_r$EXAMDATE_mod<-ymd(adni_r$EXAMDATE_mod)
Let’s make sure everything worked correctly. One way to inspect the new column is to use summary()
:
summary(adni_r$EXAMDATE_mod)
Min. 1st Qu. Median Mean 3rd Qu.
"2005-08-18" "2008-10-15" "2012-04-06" "2011-11-07" "2013-11-18"
Max.
"2019-04-25"
Key Points