Matrix <- bind vectors
Often, you won't be creating vectors like we did in the last example. Instead, you will create them from multiple vectors that you want to combine together. For this, it is easiest to use the functions cbind()
and rbind()
(column bind and row bind respectively). To see these in action, let's combine two vectors of Apple and IBM stock prices:
apple <- c(109.49, 109.90, 109.11, 109.95, 111.03)
ibm <- c(159.82, 160.02, 159.84, 160.35, 164.79)
cbind(apple, ibm)
apple ibm
[1,] 109.49 159.82
[2,] 109.90 160.02
[3,] 109.11 159.84
[4,] 109.95 160.35
[5,] 111.03 164.79
rbind(apple, ibm)
[,1] [,2] [,3] [,4] [,5]
apple 109.49 109.90 109.11 109.95 111.03
ibm 159.82 160.02 159.84 160.35 164.79
Now its your turn!
This is a part of the course
“Introduction to R for Finance”
Exercise instructions
- The
apple
,ibm
, andmicr
stock price vectors from December, 2016 are in your workspace. - Use
cbind()
to column bindapple
,ibm
, andmicr
together, in that order, ascbind_stocks
. - Print
cbind_stocks
. - Use
rbind()
to row bind the three vectors together, in the same order, asrbind_stocks
. - Print
rbind_stocks
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# cbind the vectors together
cbind_stocks <-
# Print cbind_stocks
# rbind the vectors together
rbind_stocks <-
# Print rbind_stocks
This exercise is part of the course
Introduction to R for Finance
Learn essential data structures such as lists and data frames and apply that knowledge directly to financial examples.
In this chapter, you will learn all about vectors and matrices using historical stock prices for companies like Apple and IBM. You will then be able to feel confident creating, naming, manipulating, and selecting from vectors and matrices.
Exercise 1: What is a vector?Exercise 2: c()ombineExercise 3: Coerce itExercise 4: Vector names()Exercise 5: Visualize your vectorExercise 6: Vector manipulationExercise 7: Weighted average (1)Exercise 8: Weighted average (2)Exercise 9: Weighted average (3)Exercise 10: Vector subsettingExercise 11: Matrix - a 2D vectorExercise 12: Create a matrix!Exercise 13: Matrix <- bind vectorsExercise 14: Visualize your matrixExercise 15: cor()relationExercise 16: Matrix subsettingWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.