Get startedGet started for free

Matrix subsetting

Just like vectors, matrices can be selected from and subsetted! To do this, you will again use [ ], but this time it will have two inputs. The basic structure is:

my_matrix[row, col]

Then: To select the first row and first column of stocks from the last example: stocks[1,1]

To select the entire first row, leave the col empty: stocks[1, ]

To select the first two rows: stocks[1:2, ] or stocks[c(1,2), ]

To select an entire column, leave the row empty: stocks[, 1]

You can also select an entire column by name: stocks[, "apple"]

This exercise is part of the course

Introduction to R for Finance

View Course

Exercise instructions

  • stocks is in your workspace.
  • Select the third row of stocks.
  • Select the fourth and fifth row of the ibm column of stocks.
  • Select the apple and micr columns from stocks using c() inside the brackets.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Third row


# Fourth and fifth row of the ibm column


# apple and micr columns
Edit and Run Code