What is the exact meaning of the quoted square bracket passed as a parameter for applying functions?

In the R programming language, what exactly means the meaning

'['

which serves as a parameter to sapply () and lapply () in the following part of the code:

dd <- data.frame(
    A = c(1L, 2L, 3L), 
    B = c(4L, 5L, 6L), 
    C = c("X1=7;X2=8;X3=9",
          "X1=13;X2=14",
          "X1=5;X2=1;X3=8")
)
namev <- function(x) {
    a <- strsplit(x,"=")
    setNames(sapply(a,'[',2), sapply(a,'[',1))
}

vv <- lapply(strsplit(as.character(dd$C),";"), namev)

nm <- unique(unlist(sapply(vv, names)))

#extract data from all rows for every column
nv <- do.call(rbind, lapply(vv, '[', nm))

dd $ C [1] X1 = 7; X2 = 8; X3 = 9 X1 ;; X1 = 13; X2 = 14
Levels: X1 ;; X1 = 13; X2 = 14 X1 = 7; X2 = 8; X3 = 9

@Henrik The answer to the two answers is the same, but the questions are different. The question for which this has been marked as a duplicate ( Using the '[' square bracket as a function for lapply in R ) presupposes knowing that [is a function that is not obvious to us R newbies.

+4
source share
4 answers

[ - . .

L <- list(a = 1:4, b = 1:3)

sapply(L, `[`, 2)
## a b 
## 2 2 

sapply :

sapply(L, function(x) `[`(x, 2))

sapply(L, function(x) x[2])

R, R- , C-.

`[`
## .Primitive("[")

S3. , R.

> methods("[")
 [1] [,nonStructure-method [.acf*                [.AsIs               
 [4] [.bibentry*           [.data.frame          [.Date               
 [7] [.difftime            [.Dlist               [.factor             
[10] [.formula*            [.getAnywhere*        [.hexmode            
[13] [.listof              [.noquote             [.numeric_version    
[16] [.octmode             [.pdf_doc*            [.person*            
[19] [.POSIXct             [.POSIXlt             [.raster*            
[22] [.roman*              [.SavedPlots*         [.simple.list        
[25] [.table               [.terms*              [.ts*                
[28] [.tskernel*           [.warnings           
see '?methods' for accessing help and source code

, , R :

`[.data.frame`

`[.Date`
+5

[ - .

iris[1,2] '['(iris,1,2).

, (. ?make.names).

:

'head'(iris)

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

FYI magrittr extract extract2, [ [[, ( ).

[<- [[<- , vector/matrix/data.frame/list inset inset2 magrittr

+2

, , : x[3] , "["(x, 3).

+1

, . , . :.

a <- list(c(2,5),c(24,4),c(15,3))
lapply(a,'[',2)

, 5, 4 3.

0

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


All Articles