RStudio Workshop: Creating Histograms
RStudio Workshop: Creating Histograms
It is important to work through the recordings for topic 6 before starting this workshop. The recordings
cover how to install R and RStudio, as well as how to import data.
We suggest you create a folder on your computer called Stats111. It is a good idea to save all your RStudio
work and data in this folder.
For help with RStudio, use the RStudio Guide under Software Guides in the ‘Everything Else’ folder
under Course Resources on Stream.
^ raise to a power
/ divide
* multiply
- subtract
+ add
sqrt( square root
)
The order of the list matches the correct order of operations. For example, according to BEDMAS, we
multiply before we subtract. We use brackets to control the order of calculations.
Eg: 2 + 42 × 3 = 50
This is because first the 4 is squared to get 16, then this is multiplied by 3 to get 48, and finally 2 is added.
(2 + 42) × 3 = 54
This is because what is inside the brackets gets done first. So, the 4 is squared to get 16 and then 2 is added
to that to get 18, and finally this is multiplied by 3.
Check this by doing it in RStudio. Copy and paste the following lines of code into your R script and run
them:
2 + 4^2 * 3
(2 + 4^2) * 3
1
161.111 Workshop 6: RStudio
Copy the R code and the answers into the table.
R Hint: If there are ‘invisible’ multiplication signs, you need to put them into the R code.
1. Start by downloading the Excel file [Link] to your Stats111 folder. This Excel file
contains all the data sets we will use in the workshops from this week onwards.
2. Import the petrels data from [Link] and name the data petrels in RStudio.
3. Have a look at the data. Note that this is the same dataset of 662 petrels that we explored with Excel in
Workshops 1.
There are Four categorical variables. What are they called? (Pay attention to the spelling and capital
letters as they matter in RStudio)
b. Use RStudio to calculate what proportion of the petrels were caught in catchment area A.
R Hint: we use [Link] so that RStudio treats the CatchmentArea data as categorical.
2
161.111 Workshop 6: RStudio
d. What does the bar plot tell you?
b. Update the title and horizontal axis labels with something more meaningful.
You could do this by completing the following code:
hist(petrels$TailLth, main= " ", xlab= " ")
c. What does the histogram tell you about the distribution of Tail Lengths?
e. What does the boxplot tell you about the distribution of Tail Lengths?
f. Calculate the 5 number summary, mean and standard deviation for Tail Lengths:
You can use the following code:
summary(petrels$TailLth)
sd(petrels$TailLth)
g. Use these summary statistics to add to your description of Tail Lengths from the histogram and
boxplot.
RStudio uses the labels “F” and “M” by default since that is the labels used in the petrels dataset. This
code changes the axis labels to “Female” and “Male”.
For example:
[Link]= mean(petrels$TailLth)
boxplot(petrels$TailLth,main="Tail Lengths of Petrels",ylab="Length
(mm)")
points(1,[Link],pch=4)
3
161.111 Workshop 6: RStudio
3. Change the orientation of the boxplot, from vertical to horizontal.
Use horizontal=TRUE within the plot code.
For example:
boxplot(petrels$TailLth,main="Tail Lengths of Petrels",ylab="Length
(mm)", horizontal= TRUE)
4. Mark the mean on a horizontal boxplot.
We need to have calculated the mean and given it a name. Then use points()again to mark the point
on the boxplot
For example:
[Link]= mean(petrels$TailLth)
boxplot(petrels$TailLth,main="Tail Lengths of Petrels",xlab="Length
(mm)", horizontal= TRUE)
points([Link],1,pch=10)
To enhance readability of plots analyzing categorical data in RStudio, you should use parameters within the plotting functions to add descriptive titles and axis labels. For example, when using the plot() function for a bar plot, add a main title and y-axis label using the parameters main and ylab respectively: plot(as.factor(petrels$CatchmentArea),main="Number of Petrels Caught by Catchment Area",ylab="Number of Petrels"). This clarity helps quickly convey the key aspects of the data visualized.
In RStudio, arithmetic operations follow the BEDMAS order: brackets, exponents, division and multiplication (from left to right), addition and subtraction (from left to right). For example, to calculate an expression like 2 + 4^2 * 3, RStudio would first perform the exponentiation, then multiplication, and finally the addition, resulting in 50 . You use the operators ^ for power, / for division, * for multiplication, - for subtraction, and + for addition .
The 5 number summary in RStudio, consisting of the minimum, first quartile, median, third quartile, and maximum, along with the standard deviation, provides a comprehensive overview of 'Tail Lengths' distribution. These measures reveal central tendency, spread, and potential outliers: summary(petrels$TailLth) and sd(petrels$TailLth) yield these statistics . Combining them with histogram and boxplot observations allows for detailed insight into data characteristics, such as variance and symmetry, crucial for informed analyses.
A histogram of the 'Tail Lengths' can reveal the distribution pattern of these lengths within the petrel dataset. You can assess the skewness, modality, and spread of the data. The histogram may show whether the data is normally distributed, skewed, or if there are any noticeable outliers. To enhance interpretation, titles and labels should be updated to provide context, utilizing code such as hist(petrels$TailLth, main= "Distribution of Tail Lengths", xlab= "Tail Length (mm)").
To import a dataset in RStudio, download the data (e.g., RStudioWorkshopData.xlsx), store it in a designated folder such as 'Stats111', and use RStudio to import it, creating an object name like 'petrels' . For analysis, you can create a table of counts for a categorical variable using the table() function, and then plot these using functions like plot(). For instance, table(petrels$CatchmentArea) would count occurrences of each catchment area, while plot(as.factor(petrels$CatchmentArea)) would generate a bar chart, treating CatchmentArea as a categorical variable .
Marking the mean on a plot enhances its interpretative value by providing a reference point within the data distribution, suggesting central tendency. This aids in visual comparison of the mean relative to median or other components of the plot. In RStudio, the mean can be marked using the points() function, as shown with the code: TailLth.mean= mean(petrels$TailLth); boxplot(petrels$TailLth,...); points(1,TailLth.mean,pch=4), which adds a marker on the boxplot . This visual cue assists in quick, intuitive understanding of data behavior.
Using R scripts in RStudio is crucial because it helps organize and systematically execute statistical tasks. Scripts allow for the documentation of code, facilitating reproducibility and easy modification, which is especially useful during iterative analyses. By saving scripts, such as creation and execution of plots or calculations, within a folder like Stats111, one can maintain coherence in workflow and track analytical processes between sessions . This organizational structure enhances efficiency and accuracy in data analysis projects.
In RStudio, plots can be customized to improve clarity and presentation. For categorical data, names below bars can be made more descriptive using names.arg=c() within the plot code, like plot(factor(petrels$Sex), names.arg= c("Female","Male")) to replace labels such as 'F' and 'M' with full names. Other customizations include marking specific data points like the mean on a plot using points() after plotting and rotating boxplots horizontally using the horizontal=TRUE parameter .
When importing data into RStudio, converting variables to factors ensures categorical variables are treated appropriately, enabling correct analyses and visualizations. For example, plotting a categorical variable like 'CatchmentArea' using plot(as.factor(petrels$CatchmentArea)) allows RStudio to recognize the data as categories, ensuring plots like bar charts accurately reflect distinct groups . This prevents numerical misinterpretation and provides visual clarity essential for deriving meaningful insights from categorical data.
A boxplot can display the distribution's median, quartiles, and potential outliers of 'Tail Lengths'. The box's length indicates the interquartile range, while whiskers can suggest dispersion. A boxplot can also visually highlight anomalies through outliers. In RStudio, plot with the code boxplot(petrels$TailLth, main= "Tail Lengths of Petrels", ylab= "Length (mm)"). This visualization aids in comparing the central tendency and spread, potentially supplemented by marking the mean with points() to indicate central tendency relative to the median .