R Language Creating vectors Vectors


Vectors in R can have different types (e.g. integer, logical, character). The most general way of defining a vector is by using the function vector().

vector('integer',2) # creates a vector of integers of size 2.
vector('character',2) # creates a vector of characters of size 2.
vector('logical',2) # creates a vector of logicals of size 2.

However, in R, the shorthand functions are generally more popular.

integer(2) # is the same as vector('integer',2) and creates an integer vector with two elements
character(2) # is the same as vector('integer',2) and creates an character vector with two elements
logical(2) # is the same as vector('logical',2) and creates an logical vector with two elements

Creating vectors with values, other than the default values, is also possible. Often the function c() is used for this. The c is short for combine or concatenate.

c(1, 2) # creates a integer vector of two elements: 1 and 2.
c('a', 'b') # creates a character vector of two elements: a and b.
c(T,F) # creates a logical vector of two elements: TRUE and FALSE.

Important to note here is that R interprets any integer (e.g. 1) as an integer vector of size one. The same holds for numerics (e.g. 1.1), logicals (e.g. T or F), or characters (e.g. 'a'). Therefore, you are in essence combining vectors, which in turn are vectors.

Pay attention that you always have to combine similar vectors. Otherwise, R will try to convert the vectors in vectors of the same type.

c(1,1.1,'a',T) # all types (integer, numeric, character and logical) are converted to the 'lowest' type which is character.

Finding elements in vectors can be done with the [ operator.

vec_int <- c(1,2,3)
vec_char <- c('a','b','c')
vec_int[2] # accessing the second element will return 2
vec_char[2] # accessing the second element will return 'b'

This can also be used to change values

vec_int[2] <- 5 # change the second value from 2 to 5
vec_int # returns [1] 1 5 3

Finally, the : operator (short for the function seq()) can be used to quickly create a vector of numbers.

vec_int <- 1:10
vec_int # returns [1] 1 2 3 4 5 6 7 8 9 10

This can also be used to subset vectors (from easy to more complex subsets)

vec_char <- c('a','b','c','d','e')
vec_char[2:4] # returns [1] "b" "c" "d"
vec_char[c(1,3,5)] # returns [1] "a" "c" "e"