Chapter 4 – Matrices and Dataframes

Christine Monnier

In this chapter, we are going to move away from one-dimensional data such as vectors and start working with two-dimensional or tabular data such as matrices and dataframes or datasets.

Learning Objectives

In this chapter, we will cover the following topics:

  • how to create a matrix;
  • how to add row and column names to a matrix;
  • how to add a new column to a matrix;
  • how to create a dataframe;
  • how to install libraries or packages;
  • how to load libraries or packages;
  • three different ways to load datasets.

Part 1 – Creating matrices and dataframes

In this first part, you are going to learn about matrices and dataframes, and their differences, by creating them with simple code. We will examine how to add names to the rows and columns.

Parts 2 & 3 – Installing and loading libraries and loading datasets

In order to work with dataframes, we have to know where to find them and how to load them in our environment. The video below explains first how to install and load new libraries and packages, to extend the basic R functions. And then, we will look at three different ways of loading datasets into our environment.

Now that we know how to load datasets in our environment, we are ready to start exploring and extracting information from our data. In the next chapter, we will examine simple ways of extracting basic information.

Key functions used in this chapter

Part 1

  • class(): the function that prints the class of an object (such as a matrix);
  • dim(): the function that prints the dimensions of an object (such as number of rows and columns);
  • matrix(): the function that creates a matrix;
  • rownames(): the function that creates names for the rows of a matrix or dataframe;
  • colnames(): the functions that creates names for the columns of a matrix or dataframe;
  • cbind(): the function that appends a new column to a matrix or dataframe;
  • data.frame(): the function that creates a dataframe.

Part 2

  • install.packages(): the function that installs a new library or package in R Studio;
  • library(): the function that loads a library;

Part 3

  • data(): the function that loads a dataset from a loaded library or package;
  • read.csv(): the function that reads a csv file into the environment.

Check your comprehension of this chapter’s material by taking the quiz below.

License

Icon for the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License

R and R Studio For Absolute Beginners Copyright © 2022 by Christine A Monnier is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book