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
Lecture Notes
Exercises
-- Basic Expressions --
Think about what value each of the following expressions will return? Check your answers using the R Console by typing each expression into the console on the line marked
>
and pressing enter.- 2 - 10
- 3 * 5
- 9 / 2
- 5 - 3 * 2
- (5 - 3) * 2
- 4 ** 2
- 8 / 2 ** 2
Did any of the results surprise you? If so, then might have run in to some order of operations confusion. The order of operators for math in R are the same as for mathematics more generally.
Now turn this set of expressions into a program that you can save by using an R script. For each expression add one line to the script as part of a print statement. Copy and paste the script into the console to display the answer to the screen. If you are using RStudio, you can use Ctrl+Enter (Windows & Linux) or Command+Enter (Mac) to run the line or selection of code directly from your script.
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:[click here for output]# Exercise 1 print(2-10)
-- Basic Variables --
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 print(mass_g)
Modify this code to create a variable that stores a body mass in pounds and assign it a value of 3.5 (about record size of a Pile Surfperch caught in Washington. Convert this value to kilograms (we are serious scientists after all). There are approximately 2.2046 lbs in a kilogram, so divide the variable storing the weight in pounds by 2.2046 and store this value in a new variable for storing mass in kilograms. Print the value of the new variable to the screen.
[click here for output]-- More Variables --
Calculate a total biomass in grams for 3 large Pacific oysters (Crassostrea gigas) 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 Crassostrea gigas. - Create a variable
number
and assign it the number of individuals. - Create a variable
biomass
and assign it a value by multiplying the two 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.
Are the variable names
grams
,number
, andbiomass
the best choice? If we came back to the code for this assignment in two weeks (without the assignment itself in hand) 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 rename the variables in your program to what you find most useful. Make sure your code still runs properly after you’ve changed the names.
[click here for output]-- Built-in Functions --
A built-in function is one that you don’t need to install and load a package to use. To learn how to use a function use the
help()
function.help()
takes one parameter, the name of the function that you want information about (e.g.,help(abs)
). Familiarize yourself with the built-in functionsabs()
,round()
,sqrt()
,tolower()
, andtoupper()
. Use these built-in functions to print the following items:- The absolute value of -15.5.
- 4.483847 rounded to one decimal place. The function
round()
takes two arguments, the number to be rounded and the number of decimal places. - 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.
- 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
sqrt()
call inside theround()
call.
-- Modify the Code --
The following code calculates the total net primary productivity (NPP) per day for two sites based on the grams of carbon produced per square meter per day, and the total area of the sites, and prints them out.
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 print(site1_npp_day) print(site2_npp_day)
Modify the code to produce the following items and print them out in order:
- The sum of the total daily NPP for the two sites combined.
- The difference between the total 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.
-- Code Shuffle --
We are interested in understanding the monthly variation in precipitation in Gainesville, FL. We’ll use some data from the NOAA National Climatic Data Center.
Start by creating a
data
directory in the same directory as your homework script(s) and then downloading the data and saving it to thisdata
directory.Each row of this data file is a year (from 1961-2013) and each column is a month (January - December).
Rearrange the following program so that it:
- Imports the data
- Calculates the average precipitation in each month across years
- Plots the monthly averages as a simple line plot
Finally, add a comment above the code that describes what it does. The comment character in R is
#
.plot(monthly_mean_ppt, type = "l", xlab = "Month", ylab = "Mean Precipitation") monthly_mean_ppt <- colMeans(ppt_data) ppt_data <- read.csv("data/gainesville-precip.csv", header = FALSE)
It’s OK if you don’t know exactly how the details of the program work at this point, you just need to figure out the right order based on when variables are defined and when they are used.
[click here for output]-- Bird Banding --
The number of birds banded at a series of sampling sites has been counted by your field crew and entered into the following vector. Counts are entered in order and sites are numbered starting at one. Cut and paste the list into your assignment and then answer the following questions by printing them to the screen. Some R functions that will come in handy include
length()
,max()
,min()
,sum()
, andmean()
.number_of_birds <- c(28, 32, 1, 0, 10, 22, 30, 19, 145, 27, 36, 25, 9, 38, 21, 12, 122, 87, 36, 3, 0, 5, 55, 62, 98, 32, 900, 33, 14, 39, 56, 81, 29, 38, 1, 0, 143, 37, 98, 77, 92, 83, 34, 98, 40, 45, 51, 17, 22, 37, 48, 38, 91, 73, 54, 46, 102, 273, 600, 10, 11)
- How many sites are there?
- How many birds were counted at site 42?
- How many birds were counted at the last site? Have the computer choose the last site automatically in some way, not by manually entering its position.
- What is the total number of birds counted across all of the sites?
- What is the smallest number of birds counted?
- What is the largest number of birds counted?
- What is the average number of birds seen at a site?
-- Shrub Volume Vectors --
You have data on the length, width, and height 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, 2.8, 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 (i.e., the length times the width times the height).
- The total volume of all of the shrubs.
- A vector of the height of shrubs with lengths greater than 2.5.
-- Shrub Volume Data Frame --
This is a follow up to Shrub Volume Vectors.
One of your collaborators has posted a comma-delimited text file online for you to analyze. The file contains dimensions of a series of shrubs (ShrubID, Length, Width, Height) and they need you to determine their volumes (
l * w * h
). You could do this using a spreadsheet, but the project that you are working on is going to be generating lots of these files so you decide to write a program to automate the process.Download the data, use
read.csv()
to import it into R, and then use the$
operator to print out:- The shrub lengths
- The volume of each of the shrubs