Matrices and Data Frames in R
By: Karthik Janar
In this tutorial, weâ€™ll cover matrices and data frames. Both represent â€˜rectangularâ€™ data types, meaning that they are used to store tabular data, with rows and columns. The main difference, as youâ€™ll see, is that matrices can only contain a single class of data, while data frames can consist of many different classes of data.
Letâ€™s create a vector containing the numbers 1 through 20 using the :
operator. Store the result in a variable called my_vector. You learned about the :
operator in the tutorial on sequences. If you wanted to create a vector containing the numbers 1, 2, and 3 (in that order), you could use either c(1, 2, 3) or 1:3. In this case, we want the numbers 1 through 20 stored in a variable called my_vector. Also, remember that you donâ€™t need the c() function when using :
.
my_vector <- 1:20
my_vector
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
The dim() function tells us the â€˜dimensionsâ€™ of an object. What happens if we do dim(my_vector)?
dim(my_vector)
## NULL
Clearly, thatâ€™s not very helpful! Since my_vector is a vector, it doesnâ€™t have a dim
attribute (so itâ€™s just NULL), but we can find its length using the length() function.
length(my_vector)
## [1] 20
What happens if we give my_vector a dim
attribute? Letâ€™s give it a try.
dim(my_vector) <- c(4,5)
The dim() function allows you to get OR set the dim
attribute for an R object. In this case, we assigned the value c(4, 5) to the dim
attribute of my_vector.
Use dim(my_vector) to confirm that weâ€™ve set the dim
attribute correctly.
dim(my_vector)
## [1] 4 5
Another way to see this is by calling the attributes() function on my_vector. Try it now.
attributes(my_vector)
## $dim
## [1] 4 5
When dealing with a 2-dimensional object (think rectangular table), the first number is the number of rows and the second is the number of columns. Therefore, we just gave my_vector 4 rows and 5 columns.
But, wait! That doesnâ€™t sound like a vector any more. Well, itâ€™s not. Now itâ€™s a matrix. View the contents of my_vector now to see what it looks like.
my_vector
## [,1] [,2] [,3] [,4] [,5]
## [1,] 1 5 9 13 17
## [2,] 2 6 10 14 18
## [3,] 3 7 11 15 19
## [4,] 4 8 12 16 20
Now, letâ€™s confirm itâ€™s actually a matrix by using the class() function.
class(my_vector)
## [1] "matrix"
Sure enough, my_vector is now a matrix. We should store it in a new variable that helps us remember what it is. Store the value of my_vector in a new variable called my_matrix.
my_matrix <- my_vector
The example that weâ€™ve used so far was meant to illustrate the point that a matrix is simply an atomic vector with a dimension attribute. A more direct method of creating the same matrix uses the matrix() function.
If your RStudio is open, bring up the help file for the matrix() function now using the ?
function.
#?matrix
Now, look at the documentation for the matrix function and see if you can figure out how to create a matrix containing the same numbers (1-20) and dimensions (4 rows, 5 columns) by calling the matrix() function. Store the result in a variable called my_matrix2.
my_matrix2 <- matrix(data=1:20, nrow=4, ncol=5)
Finally, letâ€™s confirm that my_matrix and my_matrix2 are actually identical. The identical() function will tell us if its first two arguments are the same. Try it out.
identical(my_matrix,my_matrix2)
## [1] TRUE
Now, imagine that the numbers in our table represent some measurements from a clinical experiment, where each row represents one patient and each column represents one variable for which measurements were taken.
We may want to label the rows, so that we know which numbers belong to each patient in the experiment. One way to do this is to add a column to the matrix, which contains the names of all four people.
Letâ€™s start by creating a character vector containing the names of our patients â€“ Bill, Gina, Kelly, and Sean. Remember that double quotes tell R that something is a character string. Store the result in a variable called patients.
patients <- c("Andy", "Bob", "Charles", "Danny")
Now weâ€™ll use the cbind() function to â€˜combine columnsâ€™. Donâ€™t worry about storing the result in a new variable. Just call cbind() with two arguments â€“ the patients vector and my_matrix.
cbind(patients, my_matrix)
## patients
## [1,] "Andy" "1" "5" "9" "13" "17"
## [2,] "Bob" "2" "6" "10" "14" "18"
## [3,] "Charles" "3" "7" "11" "15" "19"
## [4,] "Danny" "4" "8" "12" "16" "20"
Something is fishy about our result! It appears that combining the character vector with our matrix of numberscaused everything to be enclosed in double quotes. This means weâ€™re left with a matrix of character strings, which is no good.
If you remember back to the beginning of this tutorial, we saw that matrices can only contain ONE class of data. Therefore, when we tried to combine a character vector with a numeric matrix, R was forced to â€˜coerceâ€™ the numbers to characters, hence the double quotes.
This is called â€˜implicit coercionâ€™, because we didnâ€™t ask for it. It just happened.
So, weâ€™re still left with the question of how to include the names of our patients in the table without destroying the integrity of our numeric data. Thats where the data.frame comes into picture.
my_data <- data.frame(patients, my_matrix)
my_data
## patients X1 X2 X3 X4 X5
## 1 Andy 1 5 9 13 17
## 2 Bob 2 6 10 14 18
## 3 Charles 3 7 11 15 19
## 4 Danny 4 8 12 16 20
It looks like the data.frame() function allowed us to store our character vector of names right alongside our matrix of numbers. Thatâ€™s exactly what we were hoping for!
Behind the scenes, the data.frame() function takes any number of arguments and returns a single object of class data.frame
that is composed of the original objects.
Letâ€™s confirm this by calling the class() function on our newly created data frame.
class(my_data)
## [1] "data.frame"
Itâ€™s also possible to assign names to the individual rows and columns of a data frame, which presents another possible way of determining which row of values in our table belongs to each patient.
However, since weâ€™ve already solved that problem, letâ€™s solve a different problem by assigning names to the columns of our data frame so that we know what type of measurement each column represents.
Since we have six columns (including patient names), weâ€™ll need to first create a vector containing one element for each column. Create a character vector called cnames that contains the following values (in order) â€“ â€œpatientâ€, â€œageâ€, â€œweightâ€, â€œbpâ€, â€œratingâ€, â€œtestâ€.
cnames <- c("patient", "age", "weight", "bp", "rating", "test")
Now, use the colnames() function to set the colnames
attribute for our data frame. This is similar to the way we used the dim() function earlier in this tutorial.
colnames(my_data) <- cnames
Print the contents of my_data.
my_data
## patient age weight bp rating test
## 1 Andy 1 5 9 13 17
## 2 Bob 2 6 10 14 18
## 3 Charles 3 7 11 15 19
## 4 Danny 4 8 12 16 20
In this tutorial, you learned the basics of working with two very important and common data structures â€“ matrices and data frames.
Archived Comments
Most Viewed Articles (in Data Science ) Introduction to logical operations in R Manipulating Data with dplyr in R Types of Data Science Questions? Functions in R - Creating your first R function Data Analytics - Which programming language to learn. R vs Python Logical and Character Vectors in R |
Latest Articles (in Data Science) |
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview