Sub setting R Objects
In R Programming Language, subsetting allows the user to access elements from an object.
In this, we will focus on how to extract subsets from R objects.
There are three operators available for this purpose, those are,
[ ]Operator[[ ]]Operator$Operator
[ ] Operator:
[ ] operator is used to extract element(s) from an object. This allows us to extract multiple elements of an object.
Vectors are basic objects in R and they can be subsetted using the [ ] operator.
The ‘-’ sign is used to access all other indexes of the vector.
Example:
> x <- c("a", "b", "c", "d", "e", "f")
> print(x[1]) # Extract the first element
[1] "a"
> print(x[2]) # Extract the second element
[1] "b"
> print(x[1:4]) # Extract the multiple elements
[1] "a" "b" "c" "d"
> print(x[c(1,2,3)])
[1] "a" "b" "c"
> print(x[-c(1,2,3)])
[1] "d" "e" "f"
[[ ]] Operator:
[[ ]] operator is used for subsetting of list-objects. This operator is the same as [ ] operator but the only difference is that [[ ]] selects only one element whereas [ ] operator can select more than 1 element in a single command.
Example:
> ls <- list(501,"Madhu",21)
> print(ls[[1]]) # To access First element
[1] 501
> print(ls[[2]]) # To access Second element
[1] "Madhu"
[[ ]]operator is mainly used to extract nested element of a list.
Example:
> std <- list(502,"Kiran",c(85,89,86))
> print(std[[3]]) # To access Third element
[1] 85 89 86
> print(std[[3]][[2]]) # To access second element of third element
[1] 89
$ Operator:
$ operator can be used for lists and data frames in R. Unlike [ ] operator, it selects only a single element at a time. It can be used to access an element in a named list or a column in a data frame.
It is used for extracting named elements from a list or data frame. And it returns a single column (vector) when applied to a data frame.
Example:
> std <- list(sno = 502, name = "Kiran", marks = c(85,89,86))
> print(std$sno) # To access sno
[1] 502
> print(std$name) # To access name
[1] "Kiran"
> print(std$marks) # To access marks
[1] 85 89 86
> print(std$marks[[2]]) # To access second element of marks
[1] 89
Example:
> df <- data.frame(Number = c(501,502,503),
+ Name = c("Madhu","Durga","Naveen"),
+ Marks = c(67,77,87))
> print(df$Name) # To access Names
[1] "Madhu" "Durga" "Naveen"
> print(df$Number) # To access Numbers
[1] 501 502 503
> print(df$Number[2]) # To access Number of second student
[1] 502
> print(df$Name[2]) # To access Name of second student
[1] "Durga"
> print(df$Marks[2]) # To access Marks of second student
[1] 77
Key Differences:
| Operator | Works on | Returns | Example |
|---|---|---|---|
[ ] | Vectors, Lists, Data Frames | Subset of object | x[1:2] |
[[ ]] | Lists, Data Frames | Single element | my_list[[2]] |
$ | Lists, Data Frames | Named element | df$age |