Practicing Assignment and Functions

Hello and welcome to your first R exercises!

To complete these, please open RSTudio and create a NEW text file. Make sure that you save it with a .R at the end of the file name, since that’s how RStudio knows the file is for R code.

Then complete the following exercises in that text file, using comments (lines that start with #) to explain what each line does.

Exercise 1: Assigning values

  1. Assign the numeric value of your age to a variable called my_age.

  2. The average life span of for a person in the world is about 72 years. Create a new variable (you can call it whatever you want) that stores what proportion of that average life span you’ve already lived. A little morbid, I know, sorry! Inventing exercises is hard! :)

Exercise 2: Functions!

  1. Use print() to print out the value you calculated above.

  2. Multiple that share by 100 to get the percentage of the average life span you’ve lived. Use print() and round() to print out that percentage with no decimal places.

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.