Saturday, January 13, 2018

What is Vector Indexing in R Programming and How to form a SubVector

How to form a SubVector with Vector Indexing in R Programming
One of the most important and frequently used operations in R is that of indexing vectors, in which we form a SubVector by picking elements of the given vector for specific indices or index positions. The format is Vector1[Vector2], with the result that we select those elements of Vector1 whose indices are given in Vector2.
Example :
> y <- c(1.2, 3.9, 0.4, 0.12)
> y
[1] 1.20 3.90 0.40 0.12

# Extracting elements 1 and 3 of y
> y[c(1,3)] 
[1] 1.2 0.4

# Extracting elements 3 and 4 of y
> y <- c(1.2, 3.9, 0.4, 0.12)
> v <- 3:4
> y[v]

[1] 0.40 0.12
> y[3:4]
[1] 0.40 0.12

#Please Note that the duplicates are also allowed in SubVector.
> x <- c(4,2,17,5)
> y <- x[c(1,1,3)]
> y
[1] 4 4 17

Negative Subscripts
Negative subscripts mean that we want to exclude the given elements in our output.
> z <- c(5,12,13)
> z
[1]  5 12 13
# excluding a element in output.
> z[-2]
[1]  5 13

#Please note that the Elements will exclude only in Output but not from the actual source Vector.
> z
[1]  5 12 13

To exclude elements, it is often useful to use the length() function. For instance, suppose we wish to pick up all elements of a vector z except for the last. The following code will do just that:
> z <- c(5,12,13)
> z[1:(length(z)-1)]
[1] 5 12
or you can write simply as below, where we passing the length of z as negative index z[-3] .
> z[-length(z)]
[1] 5 12


--------------------------------------------------------------------------------------------------------
Thanks, TAMATAM ; Business Intelligence & Analytics Professional
--------------------------------------------------------------------------------------------------------

No comments:

Post a Comment

Hi User, Thank You for visiting My Blog. Please post your genuine Feedback or comments only related to this Blog Posts. Please do not post any Spam comments or Advertising kind of comments which will be Ignored.