Vector Exercises

Exercise 1: Favorite Numbers

  1. make a vector called my_favorite_numbers with at least 6 of your favorite numbers. (hint: use the c() function to concatenate or combine numbers into a vector)

[1]:
my_favorite_numbers <- c(42, 47, 101, -2, 0, 30)
  1. use the mean function to find out the average of your favorite numbers.

[2]:
mean(my_favorite_numbers)
36.3333333333333
  1. How many numbers did you put in your vector? Find out using the length function!

[3]:
length(my_favorite_numbers)
6
  1. Create a vector will all the numbers from 1-10 without typing out all the numbers from 1 to 10.

[4]:
# Either:
first_ten <- 1:10
[5]:
# Or:
first_ten <- seq(1, 10)
  1. Now double all the values of first_ten in one operation.

[6]:
first_ten <- first_ten * 2

Exercise 2: Subsetting Your Favorites

Now suppose you only want the big values of my_favorite_numbers.

  1. First, let’s make a vector of true/false logical vectors. Create a logical vector that is true if the number is greater than 5 called big. If you look at big, do the values make sense?

[7]:
big <- my_favorite_numbers > 5
big
  1. TRUE
  2. TRUE
  3. TRUE
  4. FALSE
  5. FALSE
  6. TRUE
  1. Now use big to return only the values of my_favorite_numbers that are greater than 5.

[8]:
my_favorite_numbers[big]
  1. 42
  2. 47
  3. 101
  4. 30
  1. Now, using the same logic, try and get all the values of my_favorite_numbers that are bigger than the average of my_favorite_numbers. (Hint: you’ll need to use a function we’ve seen.)

[9]:
# In separate steps:
avg <- mean(my_favorite_numbers)
above_avg <- my_favorite_numbers > avg
my_favorite_numbers[above_avg]
  1. 42
  2. 47
  3. 101
  1. Now, if you used more than one line to do number 3, try and do it in one line of code.

[12]:
my_favorite_numbers[my_favorite_numbers > mean(my_favorite_numbers)]
  1. 42
  2. 47
  3. 101