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)

  2. use the mean function to find out the average of your favorite numbers.

  3. How many numbers did you put in your vector? Find out using the length function!

  4. Create a vector will all the numbers from 1-10 without typing out all the numbers from 1 to 10.

  5. Now double all the values of first_ten in one operation.

  6. Now create a new variable by adding first_ten to itself.

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?

  2. Now use big to return only the values of my_favorite_numbers that are greater than 5.

  3. 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.)

  4. Now, if you used more than one line to do number 3, try and do it in one line of code.

Solutions

Here’s the deal with programming: the only way to learn to program is to wrestle with solving your own problems. The best way to learn is to do so actively – if you just look at answers as soon as you get stuck, your process is more passive. You may feel like you’re learning more, but research shows that that’s an illusion – students who learn passively think they’re learning more than they are (a summary of work in this area is here).

Moreover, in coding in particular, the process of debugging your code is a critical skill in and of itself, and the only way you will learn to do it is by literally spending hours working through your own problems. And once you’ve seen an answer, there’s no way to unsee it, so proceed only if you absolutely have to.

OK, if you still want to proceed, you can find solutions here.