Vectors

What are vectors and where do we use them? The term vector is directly derived from the algebra field, but we shouldn't take the analogy too much further than that since within the R world, we can simply consider a vector to be an ordered sequence of values of the same data type. A sequence is ordered such that the two sequences represented below are treated as two different entities by R:

   

How do you create a vector in R? A vector is created through the c() function, as in the following statement:

c(100,20,40,15,90)

Even if this is a regular vector, it will disappear as long as it is printed out by the console. If you want to store it in your R environment, you should assign it a name, that is, you should create a variable. This is easily done by the assignment operator:

vector <- c(100,20,40,15,90)

As soon as you run this command, your environment will be enriched by a new object of type vector. This is fine, but what is the practical usage of vectors? Almost every input and output produced by R can be reduced to a vector, meaning it represents the foundation for every development of this language. Within this book, for instance, we are going to store the results of statistical tests performed on our data in vectors, and create a vector representing a probability distribution we want our model to respect.

A final relevant note on vectors—so far, we have seen only a numerical vector, but you should be aware that it is possible to define all of the following types of vectors:

Type Example
numeric 1
logical / Boolean TRUE
character "text here"

Moreover, it is possible to define mixed content vectors:

mixed_vector <- c( 1, TRUE, "text here")

To be exact, by the end these kinds of vectors will be forced to a vector of the type that can contain all the others, like character in our example, but I do not want to confuse you with too many details.

So, now we know how to create a vector and what to store within it, but how do we recall it and show its content? As a general rule, recalling an object will simply require you to write down its name. So, to show the mixed_vector we just created, it will be sufficient to write down its name within the R console and submit this minimal command. The result will be the following:

[1] "1"         "TRUE"      "text here"
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset