Explain how to perform vector indexing and slicing in R.

901    Asked by IreneEllison in Data Science , Asked on Nov 21, 2019
Answered by Irene Ellison

Indexing is defined as selecting an element from a vector present in a particular index. In R, indexing starts from 1 and is denoted by [] bracket

On the other hand, slicing is defined as selecting a part of elements present in a vector by denoting the index notation.

To perform vector indexing and slicing, we have to assign a vector

v1 <- c(100,200,300)

v2 <- c('a','b','c')

Indexing works by using brackets and passing the index position of the element as a number.

# Grab second element

v1[2]

Output: 200

v2[2]

Output: 'b'

We can perform multiple indexing also.

v1[c(1,2)]

Output: 100 200

To perform slicing we can use a colon (:) to indicate a slice of a vector. The format is:

vector[start_index:stop_index]

v <- c(1,2,3,4,5,6,7,8,9,10)

v[2:4]

Output: 2 3 4



Your Answer

Interviews

Parent Categories