## Example

Consider the below vector −

> set.seed(1)
> x1<-sample(1:10,20,replace=TRUE)
> x1
[1] 9 4 7 1 2 7 2 3 1 5 5 10 6 10 7 9 5 5 9 9
> names(x1)<-LETTERS[1:20]
> x1
A B C D E F G H I J K L M N O P Q R S T
9 4 7 1 2 7 2 3 1 5 5 10 6 10 7 9 5 5 9 9
> x1$K Error in x1$K : $operator is invalid for atomic vectors Here, we are getting the error that “$ operator is invalid for atomic vectors”. Now we should access the elements of the vector x1 with single square brackets as shown below −

> x1["K"]
K
5
> x1["T"]
T
9
> x1["A"]
A
9
> x1[1]
A
9

Let’s have a look at one more example −

> x2<-sample(1:100,10)
> x2
[1] 37 34 89 44 79 33 84 35 70 74
> names(x2)<-c("A1","A2","A3","A4","A5","A6","A7","A8","A9","A10")
> x2
A1 A2 A3 A4 A5 A6 A7 A8 A9 A10
37 34 89 44 79 33 84 35 70 74
> x2["A10"]
A10
74
> x2["A5"]
A5
79
> x2["A6"]
A6
33
> x2["A1"]
A1
37
> x2["A3"]
A3
89
Updated on 12-Aug-2020 07:20:15