R Language: Subsetting R Objects

0

Subsetting R objects is a way to extract elements from an R object. There are three operators that can be used to subset R objects: [, [[, and $.

The [ operator is the most general-purpose operator. It can be used to select multiple elements of an object, and it always returns an object of the same class as the original. For example, the following code would extract the first two elements of the vector x:

x <- c("a", "b", "c", "d", "e")

[1:2]

The [[ operator is used to extract elements of a list or a data frame. It can only be used to extract a single element, and the class of the returned object will not necessarily be a list or data frame. For example, the following code would extract the first element of the list l:

l <- list(a = 1, b = 2, c = 3)

[[1]]

The $ operator is used to extract elements of a list or a data frame by literal name. Its semantics are similar to that of [[. For example, the following code would extract the element named "a" from the list l:

l$a

Post a Comment

0Comments
Post a Comment (0)