Vector Exercises¶
Exercise 1: Favorite Numbers¶
make a vector called
my_favorite_numbers
with at least 6 of your favorite numbers. (hint: use thec()
function to concatenate or combine numbers into a vector)
[1]:
my_favorite_numbers <- c(42, 47, 101, -2, 0, 30)
use the
mean
function to find out the average of your favorite numbers.
[2]:
mean(my_favorite_numbers)
How many numbers did you put in your vector? Find out using the
length
function!
[3]:
length(my_favorite_numbers)
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)
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
.
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
calledbig
. If you look atbig
, do the values make sense?
[7]:
big <- my_favorite_numbers > 5
big
- TRUE
- TRUE
- TRUE
- FALSE
- FALSE
- TRUE
Now use
big
to return only the values ofmy_favorite_numbers
that are greater than 5.
[8]:
my_favorite_numbers[big]
- 42
- 47
- 101
- 30
Now, using the same logic, try and get all the values of
my_favorite_numbers
that are bigger than the average ofmy_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]
- 42
- 47
- 101
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)]
- 42
- 47
- 101