Practicing Assignment and Data Types

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.

[1]:
my_age <- 35
  1. 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! :)

[2]:
avg_lifespan <- 72
proportion_lived <- my_age / avg_lifespan
proportion_lived
0.486111111111111

Exercise 2: Functions!

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

[3]:
print(proportion_lived)
[1] 0.4861111
  1. 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.

[4]:
pct_lived <- proportion_lived * 100
print(round(pct_lived))
[1] 49

Exercise 3: Different types

  1. Create a variable called my_name and assign your name to it.

[5]:
my_name <- "Nick"
  1. Check the class of my_name using the class() function.

[6]:
class(my_name)
'character'
  1. Now a weird one. Create a variable called ten and assign in the value "10" in quotes. What’s the class of ten? Why is it not numeric?

[7]:
ten <- "10"
class(10)
'numeric'
  1. What happens if you add my_age and ten?

my_age + ten

> ERROR: Error in my_age + ten: non-numeric argument to binary operator
> Error in my_age + ten: non-numeric argument to binary operator
> Traceback:
  1. To convert ten to a numeric type, type ten <- as.numeric(ten). Now check it’s class again.

[8]:
ten <- as.numeric(ten)
class(ten)
'numeric'
  1. Now can you add my_age to ten?

[9]:
my_age + ten
45