myfirstvector <- c(1, 5, 3, 7)
myfirstvector[1] 1 5 3 7
To store a sequence of numbers into R, we combine the values using the combine function c() and give the sequence a name. A sequence of elements all of the same type is called a vector. To view the stored content, simply type the name of the vector.
myfirstvector <- c(1, 5, 3, 7)
myfirstvector[1] 1 5 3 7
We can perform arithmetic operations on each value of the vector. For example, to add five to each entry:
myfirstvector + 5[1] 6 10 8 12
Vectors can hold things other than numbers. They can also hold words, for example, which are of data type “character”. Words need to be written inside quotation marks, e.g. “enquoted”.
wordsvector <- c("cat", "dog", "parrot", "peppapig")
wordsvector[1] "cat" "dog" "parrot" "peppapig"
You can use either double-quote or single-quote symbols:
c("cat", "dog", "parrot", "peppapig")[1] "cat" "dog" "parrot" "peppapig"
c('cat', 'dog', 'parrot', 'peppapig')[1] "cat" "dog" "parrot" "peppapig"
The function class() will tell you the type of the object. In this case, it is a character vector.
class(wordsvector)[1] "character"
Some operations like addition and multiplication (which only make sense for numbers) will make R upset if you try them on character vectors. For example, if we try to add 5 to each word in wordsvector:
wordsvector + 5Error in wordsvector + 5 : non-numeric argument to binary operator
Finally, R requires that vectors contain elements that are all of the same type. A practical consequence of this is that, if you try to combine numbers and characters in a single vector, then R will transform all of those different things to be of the same type.
Typically, R chooses the most general or easily-convertible type between the two. In the case below, it makes everything a character—you can tell because all the elements, even the numbers, are within quotation marks.
mysecondvector <- c(4, 5, 6, "cat")
mysecondvector[1] "4" "5" "6" "cat"