0% found this document useful (0 votes)
4 views4 pages

RStudio Workshop: Creating Histograms

Uploaded by

Anika O'Connell
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views4 pages

RStudio Workshop: Creating Histograms

Uploaded by

Anika O'Connell
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

161.

111 Workshop 6: RStudio


By the end of this workshop, you will be able to use RStudio to:
• Create, open and save an R script file.
• Import a data set in RStudio.
• Create a table of a categorical variable.
• Create a histogram, boxplot and bar chart.
• Create measures of centre, spread and the 5 number summary.

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.

This workshop has three parts:


In Part A you use RStudio to do calculations.
In Part B you import data into RStudio and use it to create plots and summary statistics.
Part C is an optional extra in which you learn how to customise plots in RStudio.

Part A: Using RStudio for Arithmetic Operations


1. Open RStudio and create an R Script by clicking on the top left icon and choosing “R Script”.

2. Save this script to your Stats111 folder. Call it Workshop6.

3. Arithmetic can be carried out in RStudio using the following code:

^ 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

4. Use RStudio to calculate the answers to the following problems.

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.

Arithmetic problem R code Answer


a) (2 + 2)2 (2+2)^2
b) 52 + 64 × 25 – 30 ÷ 6 + 453 ÷ 10
c) √ 625 sqrt(625)
d) 25 + 3.2 × 0.062 ÷ (52 – 5.4)
e) (25(5 + 0.7) – 2(46 – 22)) ÷ √ 44

5. Save your R Script file.

Part B: Using RStudio to Create Plots and Summary Statistics.

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)

4. Descriptive analysis of CatchmentArea.


a. Use RStudio to create a table showing the number of petrels caught in each catchment area.
You can use the following code:
table(petrels$CatchmentArea)

b. Use RStudio to calculate what proportion of the petrels were caught in catchment area A.

c. Use RStudio to create a bar plot of catchment area.


You can use the following code:
plot([Link](petrels$CatchmentArea))

R Hint: we use [Link] so that RStudio treats the CatchmentArea data as categorical.

d. Add a label to the vertical axis and a title to the plot.


You can use the following code:
plot([Link](petrels$CatchmentArea),main="Number of Petrels
Caught by Catchment Area",ylab="Number of Petrels")

e. What does the bar plot tell you?

5. Descriptive analysis of Sex.


a. Use RStudio to create a table of the number of male and female petrels in the dataset.

b. Use RStudio to calculate what proportion of the petrels are female.

c. Use RStudio to create a bar plot of gender of the petrels.

2
161.111 Workshop 6: RStudio
d. What does the bar plot tell you?

6. Descriptive analysis of Tail Lengths.


a. Use RStudio to create a histogram of Tail Lengths.
You can use the following code:
hist(petrels$TailLth)

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?

d. Create a boxplot of Tail Lengths.


You could do this by completing the following code:
boxplot(petrels$TailLth, main= " ", ylab= " ")

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.

7. Save your R Script file.

Part C: Extra for experts.

This part is optional. It gives three ways to customise plots.

1. Customise the names plotted below each bar.


Use [Link]=c() within the plot code.
For example:
plot(factor(petrels$Sex), main= "Sex of Petrels",
ylab= "Number of Petrels", [Link]= c("Female","Male"))

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”.

2. Mark the mean on the boxplot.


First calculate the mean and give it a name. The code points()tells RStudio to mark a point on an
existing plot. We can use it here to mark the mean on the boxplot. Notice we first tell RStudio to do the
plot, then tell it to plot the point.

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)

Common questions

Powered by AI

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 .

You might also like