2

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 ?
Julien
  • 1,613
  • 1
  • 10
  • 26

4 Answers4

9

To understand the deeper meaning of "[] is actually a function"

vect[2]
# [1] 5

is equivalent to:

`[`(vect, 2)
# [1] 5

Seems you have already used the function you are looking for.

Note, that it also works for data frames/matrices.

dat
#   X1 X2 X3 X4
# 1  1  4  7 10
# 2  2  5  8 11
# 3  3  6  9 12

`[`(dat, 2, 3)
# [1] 8

`[`(dat, 2, 3, drop=F)  ## to get a data frame back
#   X3
# 2  3

Data:

vect <- c(1, 5, 4)
dat <- data.frame(matrix(1:12, 3, 4))
jay.sf
  • 60,139
  • 8
  • 53
  • 110
7

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.

Mohamed Desouky
  • 4,340
  • 2
  • 4
  • 19
3

For a data frame you can use slice:

library(dplyr)
vect = c(1, 5, 4)
vect %>% as.data.frame() %>% slice(2)
#>   .
#> 1 5
nth(vect, 2)
#> [1] 5

Created on 2022-07-10 by the reprex package (v2.0.1)

slice according to documentation:

slice() lets you index rows by their (integer) locations. It allows you to select, remove, and duplicate rows.

Quinten
  • 35,235
  • 5
  • 20
  • 53
2

We could use pluck or chuck from purrr package:

  • pluck() and chuck() implement a generalised form of [[ that allow you to index deeply and flexibly into data structures. pluck() consistently returns NULL when an element does not exist, chuck() always throws an error in that case.
library(purrr)

pluck(vect, 2)
chuck(vect, 2)

> pluck(vect, 2)
[1] 5
> chuck(vect, 2)
[1] 5
TarJae
  • 72,363
  • 6
  • 19
  • 66