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.
This exercise is part of the course
Intermediate R for Finance
Exercise instructions
- Subset
stocks
to include rows wherepanera
is greater than216
. - Subset
stocks
to retrieve the row wheredate
is equal to"2017-01-23"
. Don't forgetas.Date()
! - Subset
stocks
to retrieve rows whereibm
is less than175
andpanera
is less than216.50
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Panera range
___
# Specific date
___
# IBM and Panera joint range
___