Learning Objectives
Following this assignment students should be able to:
- execute simple math in the R console
- assign and manipulate variables
- use built-in functions for math and stats
- understand the assignment and execute flow of an R script
- understand the vector and data frame object structures
- assign, subset, and manipulate data in a vector
- execute vector algebra
- import data frames and interact with columns as vectors
Reading
Topics
- R & RStudio
- Expressions & Variables
- Types
- Errors
- Vectors & Data Frames
- Importing Data
- Readable Code
Readings
Introduction to RStudio (choose one)
- Reading: Before We Start (Data Carpentry Lesson)
- Video (15 min): An opinionated tour of RStudio (R-Ladies Sydney)
Introduction to R
Starting with Data
Lecture Notes
Exercises
Basic Expressions (10 pts)
Write the following calculations in the text editor.
- 2 - 10
- 3 * 5
- 9 / 2
- 5 - 3 * 2
- (5 - 3) * 2
- 4 ^ 2
- 8 / 2 ^ 2
Run them by either clicking the
Run
button in the top-right corner of the editor or press Ctrl+Enter (Windows & Linux) or Command+Enter (Mac) to run code and print the results in the console.If no code is highlighted/selected this will run the line the cursor is on. If you highlighted/selected a block of code it will run that entire group of lines.
You can also run the entire script by clicking the arrow next to
Source
and selectingSource with Echo
or by using Ctrl+Shift+Enter (Windows & Linux) or Command+Shift+Enter (Mac).To tell someone reading the code what this section of the code is about, add a comment line that says ‘Exercise 1’ before the code that answers the exercise. Comments in R are added by adding the
#
sign. Anything after a#
sign on the same line is ignored when the program is run. So, the start of your program should look something like:Expected outputs for Basic Expressions: 1# Exercise 1 #1.1 2 - 10 #1.2 3 * 5
Basic Variables (10 pts)
Here is a small program that converts a mass in kilograms to a mass in grams and then prints out the resulting value.
mass_kg <- 2.62 mass_g <- mass_kg * 1000 mass_g
Create similar code to convert a mass in pounds to a mass kilograms.
- Create a variable to store a body mass in pounds. Assign this variable a value of 3.5 (an appropriate mass for a Sylvilagus audubonii).
- Convert the variable from body mass in pounds to body mass in kilograms (by dividing it by 2.2046), and assign it to a new variable.
- Print the value of the new variable to the screen.
More Variables (10 pts)
Calculate a total biomass in grams for 3 white-throated woodrats (Neotoma albigula) and then convert it to kilograms. The total biomass is three times the average size of a single individual. An average individual weighs 250 grams.
- Add a new section to your R script starting with a comment.
- Create a variable
grams
and assign it the mass of a single Neotoma albigula (250). - Create a variable
number
and assign it the number of individuals (3). - Create a variable
biomass
and assign it a value by multiplying thegrams
andnumber
variables together. - Convert the value of
biomass
into kilograms (there are 1000 grams in a kilogram so divide by 1000) and assign this value to a new variable. - Print the final answer to the screen.
Built-in Functions (10 pts)
A built-in function is one that you don’t need to install and load a package to use. Some examples include:
abs()
returns the absolute value of a number (e.g.,abs(-2
))round()
, rounds a number (the first argument) to a given number of decimal places (the second argument) (e.g.,round(12.1123, 2)
)sqrt()
, takes the square root of a number (e.g.,sqrt(4)
)tolower()
, makes a string all lower case (e.g.,tolower("HELLO")
)toupper()
, makes a string all upper case (e.g.,toupper("hello")
)
Use these built-in functions to print the following items:
- The absolute value of -15.5.
- 4.483847 rounded to one decimal place.
- 3.8 rounded to the nearest integer. You don’t have to specify the number of
decimal places in this case if you don’t want to, because
round()
will default to using0
if the second argument is not provided. Look athelp(round)
or?round
to see how this is indicated. "species"
in all capital letters."SPECIES"
in all lower case letters.- Assign the value of the square root of 2.6 to a variable. Then round the variable you’ve created to 2 decimal places and assign it to another variable. Print out the rounded value.
Optional Challenge: Do the same thing as task 6 (immediately above), but instead of creating the intermediate variable, perform both the square root and the round on a single line by putting the
Expected outputs for Built-in Functions: 1sqrt()
call inside theround()
call.Modify the Code (15 pts)
The following code estimates the total net primary productivity (NPP) per day for two sites. It does this by multiplying the grams of carbon produced in a single square meter per day by the total area of the site. It then prints the daily NPP for each site.
site1_g_carbon_m2_day <- 5 site2_g_carbon_m2_day <- 2.3 site1_area_m2 <- 200 site2_area_m2 <- 450 site1_npp_day <- site1_g_carbon_m2_day * site1_area_m2 site2_npp_day <- site2_g_carbon_m2_day * site2_area_m2 site1_npp_day site2_npp_day
Copy this code into your assignment and then add additional lines of code to do the following steps and print them out after the daily NPP values (the ones currently printed by the code):
- The sum of the total daily NPP for the two sites.
- The difference between the daily NPP for the two sites. We only want an absolute difference, so use abs() function to make sure the number is positive.
- The total NPP over a year for the two sites combined (the sum of the total daily NPP values from part (1) multiplied by 365).
Basic Vectors (15 pts)
Cut and paste the following vector into your assignment and then use code to print the requested values related to the vector.
numbers <- c(5, 2, 26, 8, 16)
- The number of items in the
numbers
vector (using thelength
function) - The third item in the
numbers
vector (using[]
) - The smallest number in the
numbers
vector (using themin
function) - The largest number in the
numbers
vector (using themax
function) - The average of the numbers in the
numbers
vector (using themean
function) - The first, second and third numbers in the
numbers
vector (using[]
) - The sum of the values in the
numbers
vector (using thesum
function)
- The number of items in the
Nulls in Vectors (15 pts)
Cut and paste the following vector into your assignment. Then use code to print the requested values related to the vector. You’ll need to use
na.rm = TRUE
to ignore the null values.numbers <- c(7, 6, 22, 5, NA, 42)
- The smallest number in the
numbers
vector - The largest number in the
numbers
vector - The average of the numbers in the
numbers
- The sum of the values in the
numbers
vector
- The smallest number in the
Shrub Volume Vectors (15 pts)
You have data on the length, width, and height of 10 individuals of the yew Taxus baccata stored in the following vectors:
length <- c(2.2, 2.1, 2.7, 3.0, 3.1, 2.5, 1.9, 1.1, 3.5, 2.9) width <- c(1.3, 2.2, 1.5, 4.5, 3.1, NA, 1.8, 0.5, 2.0, 2.7) height <- c(9.6, 7.6, 2.2, 1.5, 4.0, 3.0, 4.5, 2.3, 7.5, 3.2)
Copy these vectors into an R script and then determine the following:
- The volume of each shrub (length × width × height). Storing this in a variable will make some of the next problems easier.
- The sum of the volume of all of the shrubs (using the
sum
function). - A vector of the height of shrubs with lengths > 2.5.
- A vector of the height of shrubs with heights > 5.
- A vector of the heights of the first 5 shrubs (using
[]
). - A vector of the volumes of the first 3 shrubs (using
[]
).
Optional Challenge: A vector of the volumes of the last 5 shrubs with the code written so that it will return the last 5 values regardless of the length of the vector (i.e., it will give the last 5 values if there are 10, 20, or 50 individuals).
Expected outputs for Shrub Volume Vectors: 1Variable Names (optional)
In the More Variables exercise we used the variable names
grams
,number
, andbiomass
to describe the individual mass, number of individuals, and total biomass of some white-throated woodrats. But are these variable names the best choice? If we came back to the code for this assignment in two weeks would we be able to remember what these variables were referring to and therefore what was going on in the code? The variable namebiomass
is also kind of long. If we had to type it many times it would be faster just to typeb
. We could also use really descriptive alternatives likeindividual_mass_in_grams
. Or we would compromise and abbreviate this or leave out some of the words to make it shorter (e.g.,indiv_mass_g
).Think about good variable names and then create a new version of this code with the variables renamed to be most useful. Make sure your code still runs properly with the name changes.
Expected outputs for Variable Names: