Get startedGet started for free

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

View Course

Exercise instructions

  • Subset stocks to include rows where panera is greater than 216.
  • Subset stocks to retrieve the row where date is equal to "2017-01-23". Don't forget as.Date()!
  • Subset stocks to retrieve rows where ibm is less than 175 and panera is less than 216.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
___
Edit and Run Code