Examples for 'base::Extract'


Extract or Replace Parts of an Object

Aliases: Extract Subscript [ [.listof [.simple.list [.Dlist [[ $ getElement [<- [[<- $<-

Keywords: array list

### ** Examples

x <- 1:12
m <- matrix(1:6, nrow = 2, dimnames = list(c("a", "b"), LETTERS[1:3]))
li <- list(pi = pi, e = exp(1))
x[10]                 # the tenth element of x
[1] 10
x <- x[-1]            # delete the 1st element of x
m[1,]                 # the first row of matrix m
A B C 
1 3 5 
m[1, , drop = FALSE]  # is a 1-row matrix
  A B C
a 1 3 5
m[,c(TRUE,FALSE,TRUE)]# logical indexing
  A C
a 1 5
b 2 6
m[cbind(c(1,2,1),3:1)]# matrix numeric index
[1] 5 4 1
ci <- cbind(c("a", "b", "a"), c("A", "C", "B"))
m[ci]                 # matrix character index
[1] 1 6 3
m <- m[,-1]           # delete the first column of m
li[[1]]               # the first element of list li
[1] 3.141593
y <- list(1, 2, a = 4, 5)
y[c(3, 4)]            # a list containing elements 3 and 4 of y
$a
[1] 4

[[2]]
[1] 5
y$a                   # the element of y named a
[1] 4
## non-integer indices are truncated:
(i <- 3.999999999) # "4" is printed
[1] 4
(1:5)[i]  # 3
[1] 3
## named atomic vectors, compare "[" and "[[" :
nx <- c(Abc = 123, pi = pi)
nx[1] ; nx["pi"] # keeps names, whereas "[[" does not:
Abc 
123 
      pi 
3.141593 
nx[[1]] ; nx[["pi"]]
[1] 123
[1] 3.141593
## Don't show: 
stopifnot(identical(names(nx[1]), "Abc"),
        identical(names(nx["pi"]), "pi"),
        is.null(names(nx[["Abc"]])), is.null(names(nx[[2]])))
## End(Don't show)
## recursive indexing into lists
z <- list(a = list(b = 9, c = "hello"), d = 1:5)
unlist(z)
    a.b     a.c      d1      d2      d3      d4      d5 
    "9" "hello"     "1"     "2"     "3"     "4"     "5" 
z[[c(1, 2)]]
[1] "hello"
z[[c(1, 2, 1)]]  # both "hello"
[1] "hello"
z[[c("a", "b")]] <- "new"
unlist(z)
    a.b     a.c      d1      d2      d3      d4      d5 
  "new" "hello"     "1"     "2"     "3"     "4"     "5" 
## check $ and [[ for environments
e1 <- new.env()
e1$a <- 10
e1[["a"]]
[1] 10
e1[["b"]] <- 20
e1$b
[1] 20
ls(e1)
[1] "a" "b"
## partial matching - possibly with warning :
stopifnot(identical(li$p, pi))
op <- options(warnPartialMatchDollar = TRUE)
stopifnot( identical(li$p, pi), #-- a warning
  inherits(tryCatch (li$p, warning = identity), "warning"))
Warning in li$p: partial match of 'p' to 'pi'
## revert the warning option:
if(is.null(op[[1]])) op[[1]] <- FALSE; options(op)

[Package base version 4.2.3 Index]