Using R Markdown to Display Figures and Code

In this R Markdown document, I will be writing and displaying the code used to display different types of figures, and what they tell us about the data.


Reading in the Data

First, we need to read in the dataset we will be using. We will be using the “squid.csv” dataset, a dataset with SquidGSI values taken at different points throughout the year and at different locations.

squid = read.csv("squid.csv")
head(squid)
##   Sample Year Month Location Sex     GSI
## 1      1    1     1        1   2 10.4432
## 2      2    1     1        3   2  9.8331
## 3      3    1     1        1   2  9.7356
## 4      4    1     1        1   2  9.3107
## 5      5    1     1        1   2  8.9926
## 6      6    1     1        1   2  8.7707

This reads in the dataset and allows us to understand the data by quickly previewing it.

Creating a Histogram

Now, we will create a histogram using some basic code. Histograms are very useful to see the distribution of a certain variables, in this case, SquidGSI

hist(squid$GSI, main="Squid GSI Values", xlab="Squid GSI", ylab="Frequency", col = "lightblue")

This creates an easy and quick histogram, and with a little bit of code can tell us a lot about the distribution of certain variables.

Histogram by Gender

We can also create histograms based on a certain parameter. In this case, we will create two seperate histograms, one for males, and one for females.

Male Histogram

The main section of code to note is the “[squid$Sex == 1]”, which tells R to only display a histogram for squidGSI that meets this parameter. Note that sex is a dummy variable coded to 1 = male, and 2 = female.

hist(squid$GSI[squid$Sex==1], xlab="SquidGSI Male", main="Squid GSI Values, Male", col="blue")

Squid GSI values for males.

Female Histogram

Note that now, the code is “[squid$Sex == 2]”, for female squids.

hist(squid$GSI[squid$Sex==2], xlab="SquidGSI Female", main="Squid GSI Values, Female", col="pink")

Squid GSI values for females.

Boxplots

Boxplots are another very useful data analytics tool, showing the median, 25th percentile, 75th percentile, and the inner quartile range, potentially identifying outliers.

Again, we will create two separate boxplots, one for male, and the other for female. Note that first, we create a log squid GSI variable in order to better see the small differences between gender.

The ~ means that squid GSI is a function of (~) sex, prompting R to make to different plots.

squid$log_gsi = log(squid$GSI)
boxplot(squid$log_gsi ~ Sex, data=squid, xlab="Sex", ylab="Log GSI", main="Log Squid GSI Boxplot VS Sex")
legend("bottomright", legend=c("1: Male", "2: Female"))

Boxplots for squid GSI based on gender.

Conclusion

Overall, R is a very valuable language that can be used to display awesome figures with a small amount of code, and is incredibly valuable for data analytics and telling a story in any field.