r vector access items

R – Access Items in Vector

Posted on

How To Access Items in Vector?

We can use index notation with square brackets as vector[index] to access items in vector. The index should be a single value that specifies the position of the item, or a vector of positions. This index starts at 1 and increments by 1 (1, 2, 3, and so on) until the end of vector. The return value of expression is a vector.

Syntax

x[index]

Not only we can access single item using Index, we can also access multiple items in vector using indices by passing indices as vector inside square brackets.

Example:

m <- c(51, 100, 105, 260, 125, 330)

#accessing single item
result1 <- m[2]
cat("Single Item : ", result)

#accessing multiple items
result <- m[c(2, 3, 5)]
cat("Multiple Items : ", result)

#accessing out of range items
result <- m[10]
cat("Out range Item : ", result)

#output:
Single Item :  100
Multiple Items :  100 105 125
Out range Item :  NA

Conclutions

Accessing items in vector is done using index notation with square brackets that specifies the position of the item.