In this exercise I use for loops and if statements to plot monthly global temperatures

This is done in two parts, to create different plots, highlighting different aspects of the global month temperatures. The data set “giss_temp” is used in part 1 and 2.

Part 1 - for loops

In part one we will create a for loop that loops across all years in the giss_temp data set, and plots the 12 monthly time values for each year.

Step 1: Simply read in the giss_temp file and call it “giss”

giss = read.csv("giss_temp.csv")

Step 2: Get a list of all unique years in the dataset

unique_years = unique(giss$Year)

Step 3: create a for loop, that will go over each year.

for (year in unique_years) {
  yearID = which(giss$Year == year)
  png(paste("giss_temp_", year, ".png", sep=''))
  plot(giss$Month[yearID], giss$TempAnom[yearID],
       xlab="Month", ylab="Temperature Anomaly", main=paste("Year:", year),
       pch=16, col="blue", ylim=range(giss$TempAnom, na.rm=TRUE))
  dev.off()
}

This should have automatically downloaded all of these figures to your working directory, (check to make sure)

Part 2 - if statements

in the last section, we used an ifelse statement to generate a vector of colors dependent on whether the the year is before 1980, or after 1980 and make a new figure that displays this.

Step 1: Using a new script, read in the giss_temp file again and call it “giss”

giss = read.csv("giss_temp.csv")

Step 2: Get a list of all unique years in the dataset

unique_years = unique(giss$Year)

Step 3: Use the ifelse function to plot temperature anomalies before and after 1980

  • Load the data
  • Make vector of unique year values
  • Use tapply() to estimate annual values
  • Use ifelse() to create the vector of colors
  • Plot the outcome
giss = read.csv("giss_temp.csv")

allyears = unique(giss$Year)

ann_temp = tapply(giss$TempAnom, giss$Year, mean)
mycols = ifelse( allyears < 1980, "orange", "purple")
plot(allyears, ann_temp, type = 'h', 
     col = mycols, lwd = 3,
     xlab= "Year", ylab = "T anomaly", main = "Temperature Anomalies Before vs after 1980")

The end!