What are these square brackets for S3 classes?

I got this from an open source repo on git . This shows the writing of generic and methods for S3 classes. But I do not understand the notation or conventions to which functions are assigned. Here are my questions:

  • Using backticks ``to determine the function name. Usually we did not use backticks or double quotes to assign variables / functions, but I see that this happens many times. Is this a naming convention?
  • Why is it .included before the blob name? Usually this will not be simply called blob, but the method will be method.blob?
  • Why do [brackets exist there ? Especially, [<-and [[<-. Do we fulfill some dual purpose?

Hope someone can shed some light on what ha

#' @export
 `[.blob`  <- function(x, i, ...) {
  new_blob(NextMethod())
}

#' @export
`[<-.blob` <- function(x, i, ..., value) {
  if (!is_raw_list(value)) {
    stop("RHS must be list of raw vectors", call. = FALSE)
  }

  NextMethod()
}

#' @export
 `[[<-.blob` <- function(x, i, ..., value) {
  if (!is.raw(value) && !is.null(value)) {
    stop("RHS must be raw vector or NULL", call. = FALSE)
  }

  if (is.null(value)) {
    x[i] <- list(NULL)
    x
  } else {
    NextMethod()
  }
}
+4
source share
1 answer

Summary

If you create a new object in R for which you want to use "different" subsets and assignments, you must create related methods for these operations.

  • . works as you expect - submitting a method

  • [.blob overrides the operator of the subset S3 [

  • [<-.bloboverrides operator S3 [<-(i.e. assignment of a vector subset)

  • [[<-.bloboverrides operator S3 [[<-(i.e. list assignment)

  • (, , , , ) "". , backticks, . A B A B <- 1, `A B` <- 1 (credit @r2evans)

[.blob , blob.

## Create your own blob object (class)
blob <- 1:5
attr(blob, "class") <- "blob"

## create a subset operator, which in this example just calls the next method in the s3 dispatch chain 
`[.blob` <- function(x, i, j, ...) NextMethod()

, R-

blob[3]
# [1] 3

, , , 1-

## define the function to always subset the first element
`[.blob` <- function(x, i, j, ...) { i = 1; NextMethod() }

blob 1- .

blob[1]
# [1] 1
blob[2]
# [1] 1
blob[3]
# [1] 1

, [<-

`[<-.blob` <- function(x, i, j, ...) { i = 5; NextMethod() }

5- blob

blob[1] <- 100
blob
# [1]   1   2   3   4 100
# attr(,"class")
# [1] "blob"

, / .

, [

[ <- 1:5
# Error: unexpected '[' in "["

( )

`[` <- 1:5
`[`
# [1] 1 2 3 4 5
+5

Source: https://habr.com/ru/post/1695999/


All Articles