Data Selection Essentials in R: Understanding Vectors and Matrices

Introduction and Overview

Hello there, future data expert! In this lesson, we're diving into the realm of data analysis in R. Our focus will be on extracting data from vectors and matrices. Let's start with recalling the concept of vectors and matrices. Think of them as data containers: vectors hold a row or column of data, while matrices store rows and columns, much like shelves.

We'll be picking and sorting data from vectors and matrices, mastering skills that are fundamental when dealing with real-life data, which often consists of extensive values. Are you ready to delve into data manipulation in R? Let's set sail!

Understanding the Basics of Vectors

Vectors and matrices in R are crucial data structures. Think of a vector as a line of data holding values in a single dimension. Here's how you can create a numeric vector:

R
# Create a numeric vector
ages <- c(35, 22, 48, 50, 27, 36, 25)
print(ages)

Understanding the Basics of Matrices

A matrix, on the other hand, is more akin to a table, where data is stored in rows and columns. A matrix can be created through the matrix() function, where we specify a vector and amount of rows.

R
# Create a matrix
age_height <- matrix(c(35, 22, 48, 50, 27, 36, 25, 175, 160, 180, 185, 168, 175, 170), nrow = 7)
print(age_height)

We can also specify number of columns using ncol:

R
# Create a matrix with ncol specified
age_height <- matrix(c(35, 22, 48, 50, 27, 36, 25, 175, 160, 180, 185, 168, 175, 170), ncol = 2)
print(age_height)

We can also specify both for clarity:

R
# Create a matrix with ncol and nrow specified
age_height <- matrix(c(35, 22, 48, 50, 27, 36, 25, 175, 160, 180, 185, 168, 175, 170), ncol = 2, nrow = 7)
print(age_height)

In this case, ncol * nrow should be equal to the length of the provided data vector.

The output of all three code snippets looks like this:

text
     [,1] [,2]
[1,]   35  175
[2,]   22  160
[3,]   48  180
[4,]   50  185
[5,]   27  168
[6,]   36  175
[7,]   25  170

This table contains people's age and height. Each row is one person, the first value of the row is this person's age, the second is the height.

Introduction to Selecting Data

In R, vectors and matrices have positions. The position of data values in vectors is one-dimensional and starts from 1. In matrices, data is positioned in rows and columns. So, how do you select these? The answer is simple – use their position, which is called an 'index'!

R
ages <- c(35, 22, 48, 50, 27, 36, 25)

# Select the fifth person’s age
print(ages[5]) # Output: 27
R
age_height <- matrix(c(35, 22, 48, 50, 27, 36, 25, 175, 160, 180, 185, 168, 175, 170), nrow = 7)
# Select the height (second column) of the third person
print(age_height[3, 2]) # Output: 180

The matrix in R is indexed by [row, column].

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal