x <- c("a", "b", "c", "c", "d", "a")
# Extract the first element
x[1][1] "a"
[ operatorThe [ operator always returns an object of the same class as the original:
x <- c("a", "b", "c", "c", "d", "a")
# Extract the first element
x[1][1] "a"
# other examples
x[1:4][1] "a" "b" "c" "c"
x[c(1, 3, 49)][1] "a" "c" NA
x <- 100:110
i <- c(1, 3 ,2)
x[i][1] 100 102 101
u <- x > "a"
x[u] ## or x[x > "a"]integer(0)
Subsetting a matrix:
x[1,2] ## Extract the first row, first column
x[1, ] ## Extract the first row
x[, 2] ## Extract the second column
x[1, 2, drop = FALSE] ## keeps the matrix formatIt can be used to select multiple elements of an object (also in lists or dataframes):
(x <- list(foo = 1:4, bar = 0.6, baz = "hello"))$foo
[1] 1 2 3 4
$bar
[1] 0.6
$baz
[1] "hello"
x[c(1, 3)]$foo
[1] 1 2 3 4
$baz
[1] "hello"
x["foo"]$foo
[1] 1 2 3 4
class(x["foo"])[1] "list"
x$foo[1][1] 1
x$baz[1][1] "hello"
## use of negative subscript removes first element "3"
num10[-1][[ operatorThe [[ operator is used to extract elements of a list or a dataframe. 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.
Subsetting a Dataframe:
# Use the notation [[ ]] to extract columns
x[["var1"]] = x[, 1] = x$var1 # All are equivalentSubsetting a List:
x[[1]] ## Extract single element from a list
x[["bar"]] ## Extract named index
x$bar ## Extract named index
x[[c(1, 3)]] ## Get the 3rd element of the 1st element of the list
x[[1]][[3]] ## Get the 3rd element of the 1st element of the listNow if we want to get access to the individual elements of list_obj[[2]], we have to use the following command:
(data_2variable <- data.frame(x1=c(2,3,4,5,6), x2=c(5,6,7,8,1))) x1 x2
1 2 5
2 3 6
3 4 7
4 5 8
5 6 1
(list_obj <- list(dat=data_2variable, vec.obj=c(1,2,3))) $dat
x1 x2
1 2 5
2 3 6
3 4 7
4 5 8
5 6 1
$vec.obj
[1] 1 2 3
list_obj[[2]][1][1] 1
$ operatorThe $ operator is used to extract elements of a list or data frame by literal name. Its semantics are similar to that of [[.
Example:
x[["bar"]] ## Extract named index [1] 0.6
x$bar ## Extract named index[1] 0.6