1 Introduction to R, Frequency Tables, and Graphs

1.1 Learning Goals

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

  • Open and use RStudio
  • Create objects and assign values
  • Work with different data types (numbers, text, logicals)
  • Create and manipulate vectors
  • Subset elements from vectors using indices and logical operators
  • Use built-in functions in R
  • Create frequency tables
  • Distinguish between frequency, relative frequency, and cumulative frequency
  • Create histograms and bar charts
  • Interpret graphs and frequency tables
  • Use quantile() to find percentiles

2 Part 1: Getting Started with R and RStudio

Tip: Use # for comments. Comments are notes for yourself or others, and R ignores them.

# This is a comment. R will not run this line.

2.1 Practice

  • Type your name in the YAML header at the top of this document.
  • Write a short paragraph below describing what you hope to learn in this course.

3 Part 2: Creating Objects

In R, you store information in objects using the assignment operator <-.

age <- 21
name <- "Alex"
is_student <- TRUE

Check the contents of an object by typing its name:

age
## [1] 21

3.1 Practice

  • Create an object my_age with your own age.
  • Create an object major with your field of study (as text).
  • Create an object enrolled with the value TRUE.

4 Part 3: Basic Calculations

R works like a calculator:

2 + 3
## [1] 5
10 / 2
## [1] 5
5^2
## [1] 25

You can also use objects:

age + 5
## [1] 26

4.1 Practice

  • Calculate 20 minus 7.
  • Multiply 6 by 8.
  • Create an object study_hours <- 15. Add 5 more hours to it.

5 Part 4: Working with Vectors

Vectors hold multiple values of the same type. We use c() to create homogeneous, one dimensional vectors in R.

scores <- c(85, 90, 78, 92, 88)
scores
## [1] 85 90 78 92 88

Find the mean of scores:

mean(scores)
## [1] 86.6

5.1 Practice

  • Create a vector grades with the numbers: 100, 95, 82, 76, 89.
  • Find the mean of grades.
  • Find the maximum of grades.

6 Part 5: Manipulating Vectors

6.1 (a) Changing values

grades <- c(100, 95, 82, 76, 89)
grades[2] <- 90
grades
## [1] 100  90  82  76  89

6.1.1 Quick Note About Indexing

In the code grades[2], the square brackets [] are being used for indexing (subsetting).

  • grades is a vector.
  • The number inside the brackets tells R which element(s) to return.
  • grades[2] means “give me the second element of the vector grades.”

If:

grades <- c(100, 95, 82, 76, 89)

then:

grades[2]

returns:

95

6.2 (b) Adding values

grades <- c(grades, 85)
grades
## [1] 100  90  82  76  89  85

6.3 (c) Combining vectors

extra_grades <- c(70, 88)
all_grades <- c(grades, extra_grades)
all_grades
## [1] 100  90  82  76  89  85  70  88

6.4 (d) Math with vectors

Math is applied element-by-element.

grades + 5
## [1] 105  95  87  81  94  90
grades / 2
## [1] 50.0 45.0 41.0 38.0 44.5 42.5
grades * 1.1
## [1] 110.0  99.0  90.2  83.6  97.9  93.5

6.5 Practice

  • Change the 3rd grade in grades to 100.
  • Add the value 92 at the end of grades.
  • Combine grades with a new vector makeup <- c(80, 85).
  • Increase all grades in grades by 5 points.

7 Part 6: Subsetting Vectors

7.1 (a) By position

scores[1]
## [1] 85
scores[2:4]
## [1] 90 78 92
scores[-3]
## [1] 85 90 92 88

7.2 Practice

  • Extract the second element of grades.
  • Extract the last two elements of grades.
  • Extract all elements except the first one.

7.3 (b) By logical operators

Logical subsetting returns the elements that meet a condition.

scores > 85
## [1] FALSE  TRUE FALSE  TRUE  TRUE
scores[scores > 85]
## [1] 90 92 88
scores[scores == 90]
## [1] 90
scores[scores < 90]
## [1] 85 78 88

7.4 Practice

  • Extract all grades greater than 90.
  • Extract all grades less than or equal to 90.
  • Extract all grades equal to 100.

8 Part 7: Frequency Tables

We will use a dataset of stress scores (0–20 scale) from 20 psychology students.

stress_scores <- c(3, 5, 6, 6, 7, 8, 8, 8, 9, 10,
                   10, 10, 11, 12, 12, 13, 14, 15, 16, 18)

8.1 Creating a Frequency Table

# Installing and Loading Packages

# Packages are collections of additional functions created by other R users.
# 
# For this assignment, we will use the `dplyr` package.
# 
# You only need to install a package once on your computer, but you need to load it(using library() function) every time you start a new R session.

## Step 1: Install the package

# Run this code once in R. 
install.packages("dplyr")
library(dplyr) # loads dplyr package

freq_table <- as.data.frame(table(stress_scores)) # converts table into a dataframe

colnames(freq_table) <- c("Score", "Frequency")

freq_table <- freq_table %>%
  mutate(Relative_Frequency = Frequency / sum(Frequency),
         Cumulative_Frequency = cumsum(Frequency))

freq_table

8.2 Quick Note: What does %>% mean?

The pipe operator (%>%) means “and then.” It takes the result of one step and passes it to the next step.

Example:

  1. Make a frequency table
  2. and then add relative frequency
  3. and then add cumulative frequency

8.3 Practice

  • Modify the code so that relative frequencies are displayed as percentages (0–100) instead of proportions.
  • Use round() so the percentages have one decimal place.

9 Part 8: Visualizing Frequency Data

9.1 8a. Histogram

hist(stress_scores,
     main = "Histogram of Stress Scores",
     xlab = "Stress Score",
     ylab = "Frequency",
     col = "lightblue",
     border = "black")

9.2 Practice

  • Change the histogram bars to green.
  • Add your own title beginning with “My Version:”.

You can control the number of bins using the breaks argument.

hist(stress_scores,
     breaks = 5,
     main = "Histogram with 5 bins",
     xlab = "Stress Score",
     col = "orange",
     border = "black")

9.3 Practice

  • Try breaks = 10 and breaks = 15.
  • Compare the histograms. Remember that the same data are being visualized in all cases.

9.4 8b. Bar Chart (Categorical Example)

coping <- c("Exercise","Sleep","Sleep","Music","Music",
            "Exercise","Exercise","Food","Music","Music",
            "Sleep","Food","Exercise","Music","Food",
            "Exercise","Music","Music","Sleep","Exercise")

barplot(table(coping),
        main = "Coping Strategies",
        ylab = "Frequency",
        col = "lightgreen")

9.5 Practice

  • Change the color of the bars to purple.
  • Add an x-axis label that says “Favorite Coping Strategy”.

10 Part 9: Percentiles and Percentile Ranks

Remember:

In R, we can use quantile() to find percentiles.

quantile(stress_scores, probs = c(0.25, 0.5, 0.75))
##   25%   50%   75% 
##  7.75 10.00 12.25

This gives the 25th, 50th (median), and 75th percentiles.

10.1 General Form

quantile(x, probs = c(p1, p2, p3, ...)) # do not run
  • x = your dataset
  • probs = probabilities written as decimals

Examples:

  • 0.25 = 25th percentile
  • 0.50 = 50th percentile (median)
  • 0.75 = 75th percentile

You can ask for many percentiles at once:

quantile(stress_scores, probs = seq(0, 1, 0.1))
##   0%  10%  20%  30%  40%  50%  60%  70%  80%  90% 100% 
##  3.0  5.9  6.8  8.0  8.6 10.0 10.4 12.0 13.2 15.1 18.0

10.2 Practice

  • Use quantile() to find the 10th and 90th percentiles in stress_scores.
  • Briefly explain what these percentiles tell you about the data.

11 Assignment

We will now use a new dataset so you can practice what you have learned.

The dataset below shows hours of sleep per night reported by 25 undergraduate students.

sleep_hours <- c(4.5, 5, 5.5, 6, 6.5, 6.5, 6.5, 7, 7,
                 7, 7.5, 7.5, 8, 8, 8, 8, 8.5, 9, 9,
                 9, 9.5, 10, 10, 10.5, 11)

11.1 Q1: Basic Object and Vector Practice

  • Create an object called average_sleep_goal and assign it the value 8.
  • Create a vector called weekday_sleep using the first 5 values from sleep_hours.
  • Find the mean and maximum of weekday_sleep.
  • Add 0.5 hours to every value in weekday_sleep.

11.2 Q2: Frequency Table

  • Create a frequency table with frequency, relative frequency, and cumulative frequency for sleep_hours.
  • What proportion of students sleep fewer than 7 hours?

11.3 Q3: Histogram (Default)

  • Make a histogram of the sleep_hours data.
  • Describe the shape of the distribution (symmetrical, skewed left, skewed right).

11.4 Q4: Histogram (Modify Appearance)

Modify your histogram:

  • Change the color of the bars to purple.
  • Add a new x-axis label: “Hours of Sleep per Night”
  • Add your own custom title beginning with “My Version:”.

11.5 Q5: Experiment with Bin Widths

Make histograms of sleep_hours using:

  1. breaks = 5
  2. breaks = 10
  3. breaks = 15

Then answer:

  • Which version makes the distribution easiest to understand?
  • Which version makes it harder to see the overall pattern?

11.6 Q6: Bar Chart (Categorical Example)

Suppose the same 25 students were asked their favorite time to study.

study_time <- c("Morning","Morning","Afternoon","Evening","Evening",
                "Morning","Afternoon","Afternoon","Evening","Morning",
                "Afternoon","Evening","Evening","Morning","Afternoon",
                "Evening","Evening","Morning","Morning","Afternoon",
                "Evening","Evening","Afternoon","Morning","Evening")
  • Create a bar chart for study_time.
  • Modify the chart by:
    • Changing the color of the bars to orange
    • Adding the x-axis label “Preferred Study Time”
  • Which study time is most common?

11.7 Q7: Percentiles

  • Use quantile() to find the 25th, 50th, and 75th percentiles of the sleep_hours dataset.
  • What is the percentile rank of someone who sleeps 8 hours per night?

12 Submission Instructions