본문 바로가기

카테고리 없음

[[ operator can be used with computed indices

The [[ operator can be used with computed indices; $ can only be used with literal

names.

> x <- list(foo = 1:4, bar = 0.6, baz = "hello")

> name <- "foo"

> x[[name]] ## computed index for `foo'

[1] 1 2 3 4

> x$name ## element `name' doesn't exist!

NULL

> x$foo

[1] 1 2 3 4 ## element `foo' does exist


The [[ can take an integer sequence.

> x <- list(a = list(10, 12, 14), b = c(3.14, 2.81))

> x[[c(1, 3)]]

[1] 14

> x[[1]][[3]]

[1] 14

> x[[c(2, 1)]]

[1] 3.14