Search code examples
rvectorslice

Is there a R function equivalent to the subset operator `[ ]`, in order to slice by index?


I know that [] is a function itself, but is there a function that does the following ?

vect = c(1, 5, 4)

# Slicing by row index with []
vect[2]
# [1] 5

# Does this kind of function exist ? 
slicing_func(vect, 2)
# [1] 5

# And for dataframes ?

Solution

  • You can use getElement function

    vect = c(1, 5, 4)
    
    getElement(vect, 2)
    
    #> 5
    
    

    Or you can use

    vctrs::vec_slice(vect , 2)
    
    #> 5
    

    which works for slices and data.frames too.