Logicals and subset()
Here's a fun problem. You know how to create logical vectors that tell you when a certain condition is true, but can you subset a data frame to only contains rows where that condition is true?
If you took Introduction to R for Finance, you might remember the subset() function. subset() takes as arguments a data frame (or vector/matrix) and a logical vector of which rows to return:
stocks
date ibm panera
1 2017-01-20 170.55 216.65
2 2017-01-23 171.03 216.06
3 2017-01-24 175.90 213.55
4 2017-01-25 178.29 212.22
subset(stocks, ibm < 175)
date ibm panera
1 2017-01-20 170.55 216.65
2 2017-01-23 171.03 216.06
Useful, right? The stocks data frame is available for you to use.
Cet exercice fait partie du cours
Intermediate R for Finance
Instructions
- Subset
stocksto include rows wherepanerais greater than216. - Subset
stocksto retrieve the row wheredateis equal to"2017-01-23". Don't forgetas.Date()! - Subset
stocksto retrieve rows whereibmis less than175andpanerais less than216.50.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# Panera range
___
# Specific date
___
# IBM and Panera joint range
___