开始使用免费开始使用

对因子取子集

您可以像对向量取子集一样对因子取子集。照例,[ ] 是关键!不过,当您想从分析中移除某个因子水平时,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 删除了第 1 个位置的 AAA 债券,但仍保留了 AAA 这个水平!如果您据此作图,右侧的柱状图就会出现一个空的 AAA 水平。更好的做法是让 R 完全丢弃 AAA 这个水平。为此,添加 drop = TRUE

credit_factor[-1, drop = TRUE]

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

这正是您想要的结果!

本练习是课程的一部分

R 金融入门

查看课程

练习说明

  • 使用相同的数据,从 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
编辑并运行代码