5. Retrieving data elements stored in vectors


A good thing when working with vectors is that R does not try to reorder the data elements to be stored upon assignment. This means that the order in which the elements have been concatenated remains! Thus, one can easily call any element of a vector by mentioning its position between brackets:

[code language=”r”]
data1 = c("aa","bb","cc","dd","ee")
data1[4]
[/code]

retrieve element

 

Here the fourth element in data1 has been retrieved and displayed. Note that if the result of your command is NA, it means that R did not find any data element at that position.

However, if you mention a negative position (like -4) between brackets, R retrieves all the values of the vector but omits precisely that element:

[code language=”r”]
data1 = c("aa","bb","cc","dd","ee")
data1[-4]
[/code]

remove element

 

Interestingly, you may use the function concatenate to retrieve several values in the vector, and place them in the order that you want, and in as many copies as you want. In the following example, we retrieve the elements at the first, fourth and fifth position of data1, then inverse their order, and add an extra copy of the fifth element at the end:

[code language=”r”]
data1 = c("aa","bb","cc","dd","ee")
data1

data1[c(5,4,1,5)]
[/code]

shuffle elements

 

Below is an additional way to retrieve data elements from a vector by giving them names. Let’s work on the vector data1 containing numerical value ranging from 1 to 5. Using the function names(), we provide R with a series of five names to be applied to the vector in the same order. Once that done, it is easy to retrieve the data element(s) matching the name(s) that we gave:

[code language=”r”]
data1 = c(1,2,3,4,5)
names(data1) = c("One", "Two", "Three", "Four", "Five")
data1
data1[c("Four","One")]
[/code]

names

 

  Fant du det du lette etter? Did you find this helpful?
[Average: 0]