How to deal with error “$ operator is invalid for atomic vectors” in R?

R ProgrammingServer Side ProgrammingProgramming

This error occurs because $ operator is not designed to access vector elements. If we use $ operator to access the vector elements then R does not understand it and consider it invalid, therefore, we must be very careful about where we should use $ operator. It happens when we give a name to our elements and start thinking that we can treat them as data frame columns which is a wrong approach. To access the vector elements, we should use single square brackets.

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
raja
Published on 12-Aug-2020 07:16:25
Advertisements