Values and Vectors
Vectors
Many Values at Once
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 = "")
scores ← 8, 9, 10
1scores <- c(8, 9, 10)2total <- sum(scores)values this step8, 9, 10scorestotal ← 27
1scores <- c(8, 9, 10)2total <- sum(scores)3average <- mean(scores)values this step27total8, 9, 10scoresaverage ← 9
2total <- sum(scores)3average <- mean(scores)4cat(average, "\n", sep = "")values this step9average8, 9, 10scorescat(average, " ", sep = "")
3average <- mean(scores)4cat(average, "\n", sep = "")output9values this step9average
Sum and Average
scoresstores8,9, and10.sum(scores)adds all three values.mean(scores)divides that total by the number of scores.- 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