Tutorial by Examples

Atomic vectors (which excludes lists and expressions, which are also vectors) are subset using the [ operator: # create an example vector v1 <- c("a", "b", "c", "d") # select the third element v1[3] ## [1] "c" The [ operator can also tak...
A list can be subset with [: l1 <- list(c(1, 2, 3), 'two' = c("a", "b", "c"), list(10, 20)) l1 ## [[1]] ## [1] 1 2 3 ## ## $two ## [1] "a" "b" "c" ## ## [[3]] ## [[3]][[1]] ## [1] 10 ## ## [[3]][[2]] ## [1] 20 l1[1] ##...
For each dimension of an object, the [ operator takes one argument. Vectors have one dimension and take one argument. Matrices and data frames have two dimensions and take two arguments, given as [i, j] where i is the row and j is the column. Indexing starts at 1. ## a sample matrix mat <- matr...
Subsetting a data frame into a smaller data frame can be accomplished the same as subsetting a list. > df3 <- data.frame(x = 1:3, y = c("a", "b", "c"), stringsAsFactors = FALSE) > df3 ## x y ## 1 1 a ## 2 2 b ## 3 3 c > df3[1] # Subset a varia...
The [ and [[ operators are primitive functions that are generic. This means that any object in R (specifically isTRUE(is.object(x)) --i.e. has an explicit "class" attribute) can have its own specified behaviour when subsetted; i.e. has its own methods for [ and/or [[. For example, this is...
For this example, we will use the vector: > x <- 11:20 > x [1] 11 12 13 14 15 16 17 18 19 20 R vectors are 1-indexed, so for example x[1] will return 11. We can also extract a sub-vector of x by passing a vector of indices to the bracket operator: > x[c(2,4,6)] [1] 12 14 16 ...
Let A and B be two matrices of same dimension. The operators +,-,/,*,^ when used with matrices of same dimension perform the required operations on the corresponding elements of the matrices and return a new matrix of the same dimension. These operations are usually referred to as element-wise opera...

Page 1 of 1