開始使用免費開始

Matrix <- 綁定向量

在實務上,你不一定會像上一個例子那樣直接建立矩向量。更常見的是,先有多個向量,再把它們合併起來。為了做到這件事,最方便的是使用 cbind()rbind() 這兩個函式(分別代表以欄與以列的方式綁定)。來看看範例:把 Apple 與 IBM 的股價這兩個向量合併在一起:

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

現在換你來練習!

本練習屬於課程

R for Finance 入門

檢視課程

練習說明

  • 你的工作空間中已經有 2016 年 12 月的股價向量 appleibmmicr
  • 使用 cbind() 依序將 appleibmmicr 以欄方式綁定在一起,存為 cbind_stocks
  • 列印 cbind_stocks
  • 使用 rbind() 以相同順序將三個向量以列方式綁定在一起,存為 rbind_stocks
  • 列印 rbind_stocks

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# cbind the vectors together
cbind_stocks <- 

# Print cbind_stocks


# rbind the vectors together
rbind_stocks <- 

# Print rbind_stocks
編輯並執行程式碼