Learning goals

By the end of this activity, you should be able to:

  1. Run code in an R Markdown code chunk and recognize basic R objects and functions.
  2. Explore a built-in dataset, identify a quantitative variable, and check its sample size and missing values.
  3. Create a dotplot, stemplot, histogram, and boxplot using base R (no packages required).
  4. Choose and defend a display based on the size and features of the dataset and the question being asked.
  5. Describe a distribution’s shape, center, spread, and unusual features using evidence.

Time: Approximately 55–65 minutes
Instructions: Run each code chunk using the green triangle, or use Run > Run Current Chunk. Replace # YOUR CODE HERE with working R code. Write your answers below each question. Knit to HTML when finished. Do not delete the starter code.

Important: A built-in dataset may contain several variables. In this activity, analyze one quantitative variable at a time. A dataset’s number of rows is not always the number of usable observations for a particular variable.

Part I — Meet R (about 15 minutes)

1. Calculator, comments, and assignments

Run this chunk. A line beginning with # is a comment and is not executed.

2 + 3 * 4
## [1] 14
sqrt(81)
## [1] 9
# R follows the order of operations.
observations <- c(4, 6, 6, 8, 11)
observations
## [1]  4  6  6  8 11
mean(observations)
## [1] 7

1a. What does c() do? What does <- do?
Answer: I think c() compiling the data points into one data vector. <- assigns the vector to the variable. 1b. Predict the result of median(observations) before running the next chunk. Explain how the median differs from the mean for these numbers.
Prediction and explanation: The median is the middle data point in a data set when the data is arranged from least to greatest. The mean is the average of the data set.

median(observations)
## [1] 6
mean(observations)
## [1] 7

2. Explore a built-in dataset

R comes with datasets. women has two quantitative columns: height and weight. The units are inches and pounds.

data(women)
head(women)
##   height weight
## 1     58    115
## 2     59    117
## 3     60    120
## 4     61    123
## 5     62    126
## 6     63    129
str(women)
## 'data.frame':    15 obs. of  2 variables:
##  $ height: num  58 59 60 61 62 63 64 65 66 67 ...
##  $ weight: num  115 117 120 123 126 129 132 135 139 142 ...
nrow(women)
## [1] 15
names(women)
## [1] "height" "weight"
summary(women$height)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##    58.0    61.5    65.0    65.0    68.5    72.0

2a. How many rows are in women? Which variable is being summarized by women$height?
Answer: There are 15 rows in women. The women$height is summarizing the variable height. 2b. In your own words, what do head(), str(), nrow(), and summary() tell you?
Answer: Head() displays the first 6 rows of the set, str() shows the structure of the data using numbers of the observations and variable in each column. nrow() gives total amount of rows in the data set, summary() gives a summary for each column like the man, min, mean, and median

head(women)
##   height weight
## 1     58    115
## 2     59    117
## 3     60    120
## 4     61    123
## 5     62    126
## 6     63    129
summary(women$height)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##    58.0    61.5    65.0    65.0    68.5    72.0
sd(women$height)
## [1] 4.472136

3. Missing values matter

The built-in airquality dataset contains daily air-quality measurements. Some Ozone measurements are missing (NA).

data(airquality)
nrow(airquality)
## [1] 153
sum(is.na(airquality$Ozone))
## [1] 37
mean(airquality$Ozone)             # What happens?
## [1] NA
mean(airquality$Ozone, na.rm=TRUE) # Ignore missing values
## [1] 42.12931

3a. How many rows are in airquality? How many nonmissing ozone observations are available? Show your arithmetic.
Answer: There are 153 rows in air quality, 116 nonmissing ozone observations available: 153-37=16 3b. Why is na.rm=TRUE useful?
Answer: na.rm=TRUE is useful because it tells R to focus only on the 116 observed days rather than the 37 missing days and calculates a more accurate average. ## Part II — Four ways to display one quantitative variable (about 15 minutes)

4. Dotplot: see repeated observations stack

In base R, stripchart(..., method="stack") makes a stacked dotplot. Each dot represents an observation. The mtcars dataset records the number of cylinders (cyl) for 32 cars. Because cylinder counts repeat, the dots form visible stacks.

data(mtcars)
stripchart(mtcars$cyl, method="stack", pch=19, cex=1.1,
           main="Number of Cylinders in 32 Cars",
           xlab="Number of cylinders")

4a. How many dots should appear in total? Why do several dots stack at the same value?
Answer: There should be 32 dots in total because there are 32 cars. Some dots are stacking because cylinder counts repeat and the code method="stack" tells the R to make stack vertically instead of overlapping, otherwise we wouldn’t see each individual dot. 4b. Which cylinder count is most common? How many cars have that count? Explain how the dotplot shows this.
Answer: The 8-cylinder count is the most common because it has 14 out of the 32 cars. The dotplot shows this because the dots stacked on the 8-cylinder count are taller in height compared to the other cylinder counts. 4c. Why is a dotplot especially useful for a variable with only a few distinct numerical values?
Answer: A dotplot is useful for a variable with only a few distinct numerical values because dotplots clearly graph and count precise numbers of data points and each category would have its own clean column without requiring scattered points everywhere due to large ranges. ### 5. Stemplot: preserve the actual values

stem() prints a stem-and-leaf display in the output. R chooses the scale automatically. The example uses USArrests$Murder, the murder arrest rate per 100,000 residents in each of the 50 U.S. states (1973). The rates include different decimal values, so the stemplot will have varied leaves. These are historical data, not current rates.

data(USArrests)
stem(USArrests$Murder)
## 
##   The decimal point is at the |
## 
##    0 | 8
##    2 | 11226672348
##    4 | 0349379
##    6 | 003682349
##    8 | 158007
##   10 | 04134
##   12 | 127022
##   14 | 444
##   16 | 14

5a. What information does a stemplot preserve that a histogram does not?
Answer: A stemplot can preserve individual and exact data values in a data set while a histogram only groups data into intervals that don’t give exact numbers, only the values within a certain range. 5b. Read two different murder arrest rates from the stemplot and explain how the stems and leaves combine to represent those values. Check your interpretation against sort(USArrests$Murder).
Answer: The two different murder rates are represented by the stems and leaves, showing the individual rates and their distribution. The stems represent the whole-number intervals, while the leaves represent the individual values within each interval.

sort(USArrests$Murder)
##  [1]  0.8  2.1  2.1  2.2  2.2  2.6  2.6  2.7  3.2  3.3  3.4  3.8  4.0  4.3  4.4
## [16]  4.9  5.3  5.7  5.9  6.0  6.0  6.3  6.6  6.8  7.2  7.3  7.4  7.9  8.1  8.5
## [31]  8.8  9.0  9.0  9.7 10.0 10.4 11.1 11.3 11.4 12.1 12.2 12.7 13.0 13.2 13.2
## [46] 14.4 15.4 15.4 16.1 17.4

6. Histogram: summarize a larger distribution

faithful$eruptions records eruption durations (minutes) for Old Faithful geyser. A histogram groups observations into intervals called bins.

data(faithful)
hist(faithful$eruptions, breaks=25,
     main="Old Faithful Eruption Durations",
     xlab="Duration (minutes)", ylab="Frequency")

6a. Describe the overall shape. Is there one peak or more than one?
Answer: The overall shape is bimodal with 2 peaks with one around the 2 minute mark and the other around the 4.5 minute mark. 6b. Change breaks=12 to breaks=5 and then breaks=25. How does the apparent shape change? Why must you think carefully about bin width?
Answer: When inputting breaks=5, the peaks look more right skewed than before since the graph looks bigger. Inputtting breaks=25 gives narrow bins and shows multiple unrelated peaksthat overcomplicate the data. ### 7. Boxplot: highlight quartiles and possible outliers

The built-in mtcars dataset contains fuel-efficiency measurements for 32 cars. We will examine mpg (miles per gallon), which has no observations beyond the standard 1.5 × IQR boxplot fences. This makes it easier to identify the median, quartiles, and whiskers without a large number of outlier points.

data(mtcars)
boxplot(mtcars$mpg, horizontal=TRUE,
        main="Fuel Efficiency of 32 Cars",
        xlab="Fuel efficiency (miles per gallon)")

summary(mtcars$mpg)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   10.40   15.43   19.20   20.09   22.80   33.90

7a. What does the line inside the box represent? What do the left and right edges of the box represent?
Answer: The line inside the box represents the median or quartile 2. The left edge represents quartile 1 and the right edge represents quartile 3. 7b. Are any observations plotted beyond the whiskers? Explain what the whiskers represent and why a dataset can have no flagged outliers.
Answer: There aren’t any outlier beyond the fences. Whiskers represent the minimum and maximum of a data set. The data can have no flagged outliers because all of the date values fall inside the range of the whiskers > Choosing a graph: Dotplots and stemplots make individual observations visible, especially for small or moderate datasets. Histograms help reveal the shape of a distribution, especially with many values. Boxplots efficiently show the median, quartiles, spread, and potential outliers, but can hide details such as multiple peaks. There is no single correct graph for every dataset or every question.

Part III — Make a choice, then test it (about 20 minutes)

For each case: (1) Find data of interest to display, (2) choose one of the four displays (stem, hist, dot, and box plot) as your primary graph, (3) explain why it is preferable for the stated purpose, (4) write and run code to produce it, and (5) interpret what it shows. You may use another graph afterward to check your conclusion, but identify your primary choice.

8. Case A: A small, orderly dataset (n < 30) or about

Question: What data set did you select, why and can you briefly describe the variable of interest? I selected the “women” data set because it contains a small sample of 15 observations and two clear variables with no missing values. The variable of interest is womens height.

data("women")
str(women)
## 'data.frame':    15 obs. of  2 variables:
##  $ height: num  58 59 60 61 62 63 64 65 66 67 ...
##  $ weight: num  115 117 120 123 126 129 132 135 139 142 ...
str(women$height)
##  num [1:15] 58 59 60 61 62 63 64 65 66 67 ...

Primary display and justification: I chose a box plot because I believe out of all of the graphs it’s easiet for me to understand. The variable of interest is the women’s weight as the data represents the average weight of women between 30 and 39 years old.

boxplot(women$height ,
        horizontal = TRUE ,
        col = "lavender" ,
        xlab = "Height (In)")

Interpretation The min height is around 58in, Q1 is around 62in, the median is around 65in, Q3 is around 69in, and the max height is around 72in. ### 9. Case B: A much larger data set (n > 100)

Question: What data set did you select, why, and can you briefly describe the variable of interest? The variable of interest is the womens Weight.

data("women")
str(women)
## 'data.frame':    15 obs. of  2 variables:
##  $ height: num  58 59 60 61 62 63 64 65 66 67 ...
##  $ weight: num  115 117 120 123 126 129 132 135 139 142 ...
str(women$weight)
##  num [1:15] 115 117 120 123 126 129 132 135 139 142 ...

Primary display and justification: I chose a histogram since the values are more widely spread out and higher value so to me it seemed to be best fit.

hist(women$weight ,
     main = "Distribution of Weights (n > 100)" ,
     ylab = "Values" ,
     col = "blue")

Interpretation: The data of the womens weight is right skewed, however it likely has a higher mean then median due to majority of the observations of the womens weight being from 110 to 150 pounds. ### 10. Case C: Find extraordinary observations (30 < n < 100)

Question: Find a data set with outliers. Use boxplot.stats([insertdataset]\([variable])\)out to quickly find outliers. If no outliers exists in the data set, then the command will return numeric(0). For example boxplot.stats(mtcars\(mpg)\)out returns no outliers.

boxplot.stats(cars$dist)$out
## [1] 120

Primary display and justification: I will use a box plot because then I’ll be able to point out the outliers easier and quantify how far and how much the outlier is.

boxplot(cars$dist,
        horizontal = TRUE ,
        main = "Boxplot of Car Stopping Distance" ,
        xlab = "Distance (ft)" ,
        col = "cyan")

Interpretation The data set of the Cars have 50 observations that fit the contraint, but the graph shows us that at 120 feet there is an outlier and the code confirms that. ### 11. Case D: Process of Elimination (n = any size)

Question: By now you have only one more display choice left, find a data set that works well with that display

stem(cars$speed)
## 
##   The decimal point is at the |
## 
##    4 | 00
##    6 | 00
##    8 | 00
##   10 | 00000
##   12 | 00000000
##   14 | 0000000
##   16 | 00000
##   18 | 0000000
##   20 | 00000
##   22 | 00
##   24 | 00000

Primary display and justification: A stemplot would be the best form of display because it would provide the exact data points needed.

stem(cars$speed)
## 
##   The decimal point is at the |
## 
##    4 | 00
##    6 | 00
##    8 | 00
##   10 | 00000
##   12 | 00000000
##   14 | 0000000
##   16 | 00000
##   18 | 0000000
##   20 | 00000
##   22 | 00
##   24 | 00000

Interpretation The center of the data is around 12-16 mile per hour since that’s where the peak of the plot is, meanwhile it is spread from 4 to 24 miles per hour and has no outliers or gaps.

Part IV (optional) — Challenge: graph categorical variables

12. We learned how to read data displays of one categorical variables: Bar charts, Pie Charts and two categorical variables: Segmented Bar Charts and Mosaic Plots but can you graph them?

Find a categorical variable of interest and use a data display

barplot(women$height,
        main = "Barplot of Womens Height",
        col = "pink" ,
        ylab = "Height (in)",
        xlab = "Each Woman 
        (one bar = one woman)")

Quick-reference code (use as needed)

# Examine data
head(women); str(women); summary(women$height)
length(women$height); sum(is.na(airquality$Ozone))

# Dotplot (base R)
stripchart(women$height, method="stack", pch=19,
           main="Title", xlab="Units")

# Stemplot (printed output)
stem(cars$speed)

# Histogram
hist(faithful$eruptions, breaks=12,
     main="Title", xlab="Units", ylab="Frequency")

# Horizontal boxplot
boxplot(islands, horizontal=TRUE,
        main="Title", xlab="Units")

# Ignore missing values in a numerical summary
mean(airquality$Ozone, na.rm=TRUE)

Submission: Knit this document to HTML and submit the HTML file and your completed .Rmd source file. Before submitting, make sure every required graph appears and every written response is complete.