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¶
Assign the numeric value of your age to a variable called
my_age
.
[1]:
my_age <- 35
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
Exercise 2: Functions!¶
Use
print()
to print out the value you calculated above.
[3]:
print(proportion_lived)
[1] 0.4861111
Multiple that share by 100 to get the percentage of the average life span you’ve lived. Use
print()
andround()
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¶
Create a variable called
my_name
and assign your name to it.
[5]:
my_name <- "Nick"
Check the class of
my_name
using theclass()
function.
[6]:
class(my_name)
Now a weird one. Create a variable called
ten
and assign in the value"10"
in quotes. What’s the class often
? Why is it not numeric?
[7]:
ten <- "10"
class(10)
What happens if you add
my_age
andten
?
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:
To convert
ten
to a numeric type, typeten <- as.numeric(ten)
. Now check it’s class again.
[8]:
ten <- as.numeric(ten)
class(ten)
Now can you add
my_age
toten
?
[9]:
my_age + ten