#
# CHAPTER 4: Vectors
#
# created in one of four manners --- : c seq rep
#
1:10 # a vector of the first ten integers
-3:5 # integers from -3 to 5
5:-3 # integers from 5 to -3
1:100 # integers from 1 to 100
x = 1:100 # store the integers from 1 to 100 in the vector x
4.5:25 # won't make it to 25
#
# c (combine) function: c(element1, element2, ...)
#
c(2, -3, 4, 0) # a four-element vector
x = c(2, -3, 4, 0) # x is a four-element vector
x # display x
y = c(1, NA, -3) # y is a three-element vector
y # display y
z = c(x, y, -1:3) # z is the concatenation of x, y, and -1:3
z # display z
#
# seq (sequence) function: seq(from = 1, to = 1, ...)
#
seq(2, 20, by = 2) # a vector from 2 to 20 by 2
seq(2, 20, length.out = 10) # a vector from 2 to 20 of length 10
seq(20, 1, by = -3) # a vector from 20 to 2 by -3
#
# rep (repeat) function: rep(x, times, ...)
#
rep(5, 4) # repeat 5 four times
rep(1:3, 2) # repeat 1:3 two times
rep(seq(1, 5, by = 2), 2) # repeat (1, 3, 5) two times
rep(c(1, 5), c(2, 4)) # repeat 1 twice and 5 four times
rep(seq(1, 5, 2), seq(1, 5, 2)) # one 1, then three 3s, then five 5s
rep(1:3, each = 4) # four 1s, then four 2s, then four 3s
#
# indexing: positive subscripts include; negative subscripts exclude
#
x = c(2, 0, -1, 6, # continue input
7, 8) # x is a six-element vector
x # display x
x[3] # third element of x
x[3:6] # elements 3 through 6
x[c(6, 3, 6, 1)] # elements 6, 3, 6, and 1
x[-4] # all elements except the 4th
x[-4:-6] # all elements except the 4th, 5th, and 6th
x[-c(2, 5)] # all elements except the 2nd and 5th
x[c(-2, 5)] # don't mix positive and negative indices
x[3.3] # R truncates toward zero
x[0.8] # use integer subscripts
x[-1.8] # use integer subscripts
x = NULL # set x to a vector with no elements
x # display x
x[seq(1, 9, 2)] = 11:15 # fill elements with odd subscripts only
x # display x
#
# vector arithmetic (precedence: P ^ : * / + -)
#
(1:10) + 3 # add 3 to each element of the vector
1:10 + 3 # precedence of : vs +
1:10 * 7 # multiply each element by 7
1:10 / 20 # divide each element by 20
(1:10) ^ 3 # the first ten perfect cubes
2 ^ (1:10) # the first ten powers of 2
2 ^ c(2, -3, 4, 0) # various powers of 2
x = c(-1, 0, 1) # define x
x / x # ratio of x to x
y = 4 * x # define y to be (-4, 0, 4)
x * y # product taken element-wise
y ^ x # element-wise exponentiation
z = c(y, y) # z has length 6
z # display z
z ^ x # recycle the values once you run out
y ^ c(1, 2, 3, 9) # lengths of the vectors are not multiples