1. R Basics

Q1. What is two to the power of five?

Output: 32

2^5
## [1] 32

Q2. Create a vector called stock_prices with thefollowing data points: 23,27,23,21,34.

output: 23 27 23 21 34

stock_prices <- c(23, 27, 23, 21, 34)
stock_prices
## [1] 23 27 23 21 34

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

Output:

Mon Tues Wed Thu Fri

23 27 23 21 34

names(stock_prices) <- c('Mon','Tues','Wed','Thu','Fri')
stock_prices
##  Mon Tues  Wed  Thu  Fri 
##   23   27   23   21   34

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

Output: Mon Tues Wed Thu Fri FALSE TRUE FALSE FALSE TRUE

This is actually a logical test on the elements in the stock_prices vector.

We can simply check if the vector is > 23 to return the logical test results.

over_23 <- stock_prices > 23
over_23
##   Mon  Tues   Wed   Thu   Fri 
## FALSE  TRUE FALSE FALSE  TRUE

Q5. Create a 4x3 matrix with values from 1 to 12

matrix(1:12, nrow = 4)
##      [,1] [,2] [,3]
## [1,]    1    5    9
## [2,]    2    6   10
## [3,]    3    7   11
## [4,]    4    8   12

Q6. multiple the matrix created in Q5 by 10.

m <- matrix(1:12, nrow = 4)
m * 10
##      [,1] [,2] [,3]
## [1,]   10   50   90
## [2,]   20   60  100
## [3,]   30   70  110
## [4,]   40   80  120

2. Conditional Statement

Q1. Write a script that prints "“use the force!” if the variable x is equal to 1.

hint: create a variable and assign 1 to it. Then create an if statement.

Try the if statement yourself using a different value for x.

x <- 1


ifelse(x == 1, print("use the force!"),
       print("blah blah blah"))
## [1] "use the force!"
## [1] "use the force!"

Q2. Write a script that will print “To infinity and beyond!” if the variable y is an even number.

Othewise, print “Meditate on this, I will”

Try different values of y.

y <- 3

ifelse(y %% 2 == 0,
       print("To infinity and beyond!"),
       print("Meditate on this, I will"))
## [1] "Meditate on this, I will"
## [1] "Meditate on this, I will"