開始使用免費開始

因子子集合

你可以用和向量相似的方式來對因子做子集合。照慣例,[ ] 是關鍵!不過,當你想要從分析中移除某個因子水準時,R 會有一些特別的行為。舉例來說,如果你想把投資組合中的 AAA 債券移除會怎樣?

credit_factor

[1] AAA AA  A   BBB AA  BBB A  
Levels: BBB < A < AA < AAA

credit_factor[-1]

[1] AA  A   BBB AA  BBB A  
Levels: BBB < A < AA < AAA

R 移除了第一個位置的 AAA 債券,但卻保留了 AAA 這個水準!如果你拿去繪圖,最後會得到右邊的長條圖。更好的做法是告訴 R 要把 AAA 這個水準整個丟掉。要達成這點,加入 drop = TRUE

credit_factor[-1, drop = TRUE]

[1] AA  A   BBB AA  BBB A  
Levels: BBB < A < AA

這就正是你想要的!

本練習屬於課程

R for Finance 入門

檢視課程

練習說明

  • 使用相同的資料,從 credit_factor 的第 3 與第 7 個位置移除 "A" 債券。先不要使用 drop = TRUE。將結果指定給 keep_level
  • 繪製 keep_level
  • 接著,再次從 credit_factor 中移除 "A",但這次請使用 drop = TRUE。將結果指定給 drop_level
  • 繪製 drop_level

動手互動練習

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

# Remove the A bonds at positions 3 and 7. Don't drop the A level.
keep_level <- 

# Plot keep_level


# Remove the A bonds at positions 3 and 7. Drop the A level.
drop_level <-

# Plot drop_level
編輯並執行程式碼