Home > Mobile >  Is there a R function equivalent to the subset operator [ ], in order to slice by row index?
Is there a R function equivalent to the subset operator [ ], in order to slice by row index?

Time:07-11

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 ?

CodePudding user response:

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))

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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
  • Related