Vectors

I think of a vector as an ordered column of data. It can be consist of numbers or text, but its basic construction is as an ordered column of data. The following sequences are all examples of vectors.

1:15 #generates a sequence from 1 to 15 by 1;
> [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

seq(from = 1, to = 25, by = 1) #generates a sequence from 1 to 25 by 1;
> [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

seq(1, 25, 1) #generates a sequence from 1 to 25 by 1;
> [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

Again, we can assign names to these types of objects. Below, the name X is assigned to a vector of integers from 1 to 15 and Y is assigned to a vector with three elements: 1,2,3.

X <- 1:15
Y <- 1:3
X
> [1] 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
Y
> [1] 1 2 3

The important thing is that vectors need not be sequences. Let’s assign some values to Z, using the concatenate function which takes n elements and makes them a vector using the following command: c(element 1, element 2, … , element n ).

Z <- c(143, 5640, 2601, 902, 506) 
Z
> [1] 143 5640 2601 902 506

Now the vector can be operated upon using typical mathematical functions, which are conducted element-wise meaning each element within the vector has the functino performed on it in order. Below we define a vector Z and then add ten to each element.

Z <- c(143, 5640, 2601, 902, 506) 
Z
> [1] 143 5640 2601 902 506

Z + 10
> [1] 153 5650 2611 912 516

Alternately we could square each element:

Z <- c(143, 5640, 2601, 902, 506) 
Z^2
> [1]  20449 31809600  6765201   813604   256036

However, vectors of numbers are not the only kind of vectors we can make. For example, we can make a vector of text by putting each element inside quotation marks, but we would not be ablet o perform any mathematical operations on that vector.

People <- c("Professor X.", "Professor Y.", "Professor Z.")
People
People + 6
> ## Error in People + 6: non-numeric argument to binary operator
> [1] "Professor X." "Professor Y." "Professor Z."