Most R work starts with vectors. Vector functions such as sum and mean operate over every value.

Program

Play the script to watch three scores become a total and an average.

vectors.R
Replay: real traced execution (multi-file project)
scores <- c(8, 9, 10)
total <- sum(scores)
average <- mean(scores)
cat(average, "\n", sep = "")
  1. scores ← 8, 9, 10

    1scores <- c(8, 9, 10)2total <- sum(scores)
    values this step8, 9, 10scores
  2. total ← 27

    1scores <- c(8, 9, 10)2total <- sum(scores)3average <- mean(scores)
    values this step27total8, 9, 10scores
  3. average ← 9

    2total <- sum(scores)3average <- mean(scores)4cat(average, "\n", sep = "")
    values this step9average8, 9, 10scores
  4. cat(average, " ", sep = "")

    3average <- mean(scores)4cat(average, "\n", sep = "")
    output9
    values this step9average

Sum and Average

  1. scores stores 8, 9, and 10.
  2. sum(scores) adds all three values.
  3. mean(scores) divides that total by the number of scores.
  4. The printed average is 9. | Score | Included in total? | | --- | --- | | 8 | yes | | 9 | yes | | 10 | yes |
vector `c(8, 9, 10)` creates one vector containing three numeric values.
sum `sum(scores)` adds every value in the vector.
mean `mean(scores)` computes the arithmetic average.

Exercise: vectors.R

Create a numeric score vector, compute its sum and mean, and print the average