# R Basics Exercise - Solutions¶

We will test you on a few topics:

- Basic Data Types
- Basic Arithmetic
- Vector
- Vector Operations
- Comparison operators
- Vector Selection and Indexing

The exercises below should be straightforward if you've reviewed the lecture, don't expect something very challenging yet, this is more of a review to make sure you've understood everything so far! Later on exercises/projects will be more challenging (and a lot more fun!)

### Solve the following problems using R¶

What is two to the power of five?

In [1]:

    2^5

Out[1]:
32

Create a vector called stock.prices with the following data points: 23,27,23,21,34

In [4]:

    stock.prices <- c(23,27,23,21,34)
    stock.prices

Out[4]:

1. 23
2. 27
3. 23
4. 21
5. 34

Assign names to the price data points relating to the day of the week, starting with Mon, Tue, Wed, etc...

In [6]:

    names(stock.prices) <- c('Mon','Tues','Wed','Thu','Fri')
    stock.prices

Out[6]:

Mon
  23
Tues
  27
Wed
  23
Thu
  21
Fri
  34

What was the average (mean) stock price for the week? (You may need to reference a built-in function)

In [7]:

    mean(stock.prices)

Out[7]:
25.6

Create a vector called over.23 consisting of logicals that correspond to the days where the stock price was more than $23

In [8]:

    over.23 <- stock.prices>23

Use the over.23 vector to filter out the stock.prices vector and only return the day and prices where the price was over $23

In [9]:

    stock.prices[over.23]

Out[9]:

Tues
  27
Fri
  34

Use a built-in function to find the day the price was the highest

In [10]:

    max(stock.prices)

Out[10]:
34

This didn't actually tell us the day! Only the max price, let's use a filter to grab the day!

In [15]:

    max.price <- stock.prices == max(stock.prices)
    max.price

Out[15]:

Mon
  FALSE
Tues
  FALSE
Wed
  FALSE
Thu
  FALSE
Fri
  TRUE

In [16]:

    stock.prices[max.price]

Out[16]:
Fri: 34

Okay that's it for the exercise on the basics! Great job!