Vector indexing

Elements of a vector can be arranged in several haphazard ways, which can make it difficult to access them when needed. Hence, indexing makes it easier to access the elements.

You can have any type of index vectors, from logical, integer, and character.

Vector of integers starting from 1 can be used to specify elements in a vector, and it is also possible to use negative values.

Let's see some examples of indexing:

  • Returns the nth element of x:
x <- c(9,8,1,5)
  • Returns all x values except the nth element:
x[-3]
## [1] 9 8 5

  • Returns values between a and b:
x[1:2]
## [1] 9 8
  • Returns items that are greater than a and less than b:
x[x>0 & x<4]
## [1] 1

Moreover, you can even use a logical vector. In this case, either TRUE or FALSE will be returned if an element is present at that position:

x[c(TRUE, FALSE, FALSE, TRUE)]
## [1] 9 5
..................Content has been hidden....................

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