# Working with Factors, R Beats Excel #Script to show how to work with factors. Calculates average GISS anomalies by ENSO phase ## STEP 1: SETUP library(lattice) link <-"C:/R_Home/Charts & Graphs Blog/Trend_Chart_w_Change_Pts/GISS_temp_Enso_trend.csv" # STEP 2: READ DATA GISS_Data <- read.csv(link, skip = 0, sep = ",", dec=".", row.names = NULL, header = TRUE, colClasses = c("character","numeric", "character"), comment.char="#", col.names = c("GISS_dt", "AnomC", "Enso_p")) attach(GISS_Data) ### STEP 3: Enso Factor Enso_f <- factor(Enso_p, labels=c("LaNina", "Neutral", "ElNino")) par(pty="m") #### Step 4 - Create Yr, Mo, Decade Variables GISS_yr.d <- format(as.Date(as.character(GISS_dt), format="%Y-%m-%d"),format="%Y") GISS_yr_n <- as.numeric(GISS_yr.d) GISS_dec <- (as.numeric((GISS_yr_n - 1950) %/% 10) * 10) + 1950 ### Step 5 : Plots # Boxplot to show Anomaly by Enso phase boxplot(AnomC ~ Enso_f, main = "Box & Whisker Plot: GISS Anomaly (1950 - 2008) By ENSO Phase", las = 1, pch=16, cex = 1, col = "lightblue", xlab = "ENSO Phase", ylab = expression(paste("GISS Temperature Anomaly - " , degree, "C")), ylim =c(-0.4,1.0), border = "blue", boxwex = 0.3) # Boxplot() to show distribution of temps by factor level boxplot(AnomC ~ GISS_dec, main = "Box & Whisker Plot: GISS Anomaly (1950 - 2008) By Decade", las = 1, pch=16, cex = 1, col = "lightblue", ylab = expression(paste("GISS Temperature Anomaly - " , degree, "C")), ylim =c(-0.4,1.0), border = "blue", boxwex = 0.3) # Lattice plot of Enso p and Decade xyplot(AnomC ~ GISS_dec| Enso_f, horizontal = FALSE, panel = panel.bwplot, main = "Box Plots: GISS Anomaly (1950 - 2008) By ENSO Phase and Decade", xlab = NULL, ylab = expression(paste("GISS Temperature Anomaly - " , degree, "C"))) # Summary table using tapply() Enso_mean<- tapply(AnomC, list(Enso_f, GISS_dec), FUN= "mean", digits = 1) Enso_mean ## I copied Enso_mean table to Excel and formatted it in Excel