Functions: Functions with Whole Vectors Flashcards
length()
10 students from two different classes took two exams.
function allows you to count the number of scalars in a vector
#Here are three vectors showing the data
midterm <- c(62, 68, 75, 79, 55, 62, 89, 76, 45, 67)
final <- c(78, 72, 97, 82, 60, 83, 92, 73, 50, 88)
length(midterm)
##[1] 10
adding to whole vectors
Add 5 to each midterm score (extra credit!)
midterm <- midterm + 5
midterm
##[1] 67 73 80 84 60 67 94 81 50 72
we previously made two vectors, final and midterm, and we can manipulate all of the numbers in each using simple numerical operators
subtracting whole vectors
Difference between final and midterm scores
final - midterm
##[1] 11 -1 17 -2 0 16 -2 -8 0 16
arithmetic operations on vectors
a <- c(1, 2, 3, 4, 5)
b <- c(10, 20, 30, 40, 50)
a + 100
##[1] 101 102 103 104 105
Notice how when using a vector and an arithemtic operator, the operation occurs on all of the scalars in the vector, not just on one number
operating on vectors with a single scalar
If you do an operation on a vector with a scalar, R will apply the scalar to each element in the vector
(a + b) / 10
##[1] 1.1 2.2 3.3 4.4 5.5
a ^ 2
##[1] 1 4 9 16 25 36 49 64 81 100
a <- 1:10
a / 100
##[1] 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.10
basic math with multiple vectors
a <- 1:5
b <- 1:5
ab.sum <- a + b
ab.diff <- a - b
ab.prod <- a * b
ab.sum
##[1] 2 4 6 8 10
notice how vectors are being made using existing vectors.