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!
Latihan ini adalah bagian dari kursus
Introduction to R for Finance
Petunjuk latihan
- The
apple,ibm, andmicrstock price vectors from December, 2016 are in your workspace. - Use
cbind()to column bindapple,ibm, andmicrtogether, 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.
Latihan interaktif praktis
Cobalah latihan ini dengan menyelesaikan kode contoh berikut.
# cbind the vectors together
cbind_stocks <-
# Print cbind_stocks
# rbind the vectors together
rbind_stocks <-
# Print rbind_stocks