Subsetting a factor
You can subset factors in a similar way that you subset vectors. As usual, [ ]
is the key! However, R has some interesting behavior when you want to remove a factor level from your analysis. For example, what if you wanted to remove the AAA bond from your portfolio?
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 removed the AAA bond at the first position, but left the AAA level behind! If you were to plot this, you would end up with the bar chart over to the right. A better plan would have been to tell R to drop the AAA level entirely. To do that, add drop = TRUE
:
credit_factor[-1, drop = TRUE]
[1] AA A BBB AA BBB A
Levels: BBB < A < AA
That's what you wanted!
Este exercício faz parte do curso
Introduction to R for Finance
Instruções do exercício
- Using the same data, remove the
"A"
bonds from positions 3 and 7 ofcredit_factor
. For now, do not usedrop = TRUE
. Assign this tokeep_level
. - Plot
keep_level
. - Now, remove
"A"
fromcredit_factor
again, but this time usedrop = TRUE
. Assign this todrop_level
. - Plot
drop_level
.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
# 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