在 R 中建立向量
在 R 裡,向量可以用幾種方式來建立與分析。
其中一種做法是自己建立向量,而且有多種方法可以達成。
R 的 rep() 指令會建立一個向量,將同一個元素重複指定的次數;而 seq() 指令會建立一個依照指定規律的向量。
你也可以用 c() 指令手動建立向量,c() 代表「concatenate(串接)」的意思。
本練習屬於課程
R 的資料科學線性代數
練習說明
參考建立三個
3的向量的範例,使用rep()指令建立四個4的向量。參考依序包含
2, 4, 6的向量範例,改用seq()指令建立依序包含1、3、5的向量。前兩題的提示是用
c()指令建立的。請用相同的方式,用c()指令提供前兩題的答案。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Creating three 3's and four 4's, respectively
rep(3, 3)
rep(4, ___)
# Creating a vector with the first three even numbers and the first three odd numbers
seq(2, 6, by = 2)
seq(1, 5, by = ___)
# Re-creating the previous four vectors using the 'c' command
c(3, 3, 3)
c(___, 4, ___, 4)
c(2, 4, 6)
c(___, 3, ___)