Vectors

Vectors

A vector in R is an ordered collection of values. The individual values in a vector may be referenced with an index value beginning with 1. The most basic way to create a vector is to use the c() function.

Examples


vector_1 = c(23,2,-4,7)
vector_1[3]
[1] -4


vector_2 = c("cat","dog","parrot","python")
vector_2[3]
[1] "parrot"


vector_2[3] = "hamster"
vector_2
[1] "cat"     "dog"     "hamster" "python" 

Larger from smaller

vector_3 = c(vector_1,vector_2)
vector_3
[1] "23"      "2"       "-4"      "7"       "cat"     "dog"     "hamster"
[8] "python" 


Note that a vector can only contain one type of value. R will “coerce” values to enforce this rule.

Extending a Vector

Vector_1 = c(vector_1,12)
Vector_1 
[1] 23  2 -4  7 12


Vector_1[6] = 10
Vector_1
[1] 23  2 -4  7 12 10


Vector_1[9] = 25
Vector_1
[1] 23  2 -4  7 12 10 NA NA 25

Setting and Using Names

weight = c(180,150,210)
stooges = c("Larry","Curly","Moe")
names(weight) = stooges
weight
Larry Curly   Moe 
  180   150   210 


weight["Larry"]
Larry 
  180 


weight[1]
Larry 
  180 


weight["Moe"] = 190
weight
Larry Curly   Moe 
  180   150   190 

Vectors from rep() (Repeat)

nines = rep(9,20)
nines
 [1] 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9

Vectors from seq() (Sequence)

five_to_20 = seq(from = 5,to=20,by=.5)

five_to_20
 [1]  5.0  5.5  6.0  6.5  7.0  7.5  8.0  8.5  9.0  9.5 10.0 10.5 11.0 11.5 12.0
[16] 12.5 13.0 13.5 14.0 14.5 15.0 15.5 16.0 16.5 17.0 17.5 18.0 18.5 19.0 19.5
[31] 20.0

Vectors of Integers

x = 10:25
x
 [1] 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

Elementwise Computation

x = c(1,2,3,4)
y = c(5,6,7,8)
z = x + y
z
[1]  6  8 10 12


sqrtx = sqrt(x)
sqrtx
[1] 1.000000 1.414214 1.732051 2.000000

Pieces of Vectors

y
[1] 5 6 7 8
ypart = y[2:3]
ypart
[1] 6 7


Alternatively

ypart2 = y[c(FALSE,TRUE,TRUE,FALSE)]
ypart2
[1] 6 7

The Recycling Rule

x = c(1,2,3,4)
y = c(1,-1)

x_plus_y = x + y
x_plus_y
[1] 2 1 4 3


x_times_y = x * y
x_times_y
[1]  1 -2  3 -4


part_of_x = x[c(TRUE,FALSE)]
part_of_x
[1] 1 3

A Number

A number is not just a number, it’s a vector of length 1.


x = 3
length(x)
[1] 1


length(3)
[1] 1