- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

- Related Questions & Answers
- How to deal with error invalid xlim value in base R plot?
- How to deal with “could not find function” error in R?
- How to deal with glm.fit error “NA/NaN/Inf” for logistic regression model in R?
- How to deal with the error “Error in int_abline---plot.new has not been called yet” in R?
- How to deal with error “undefined columns selected” while subsetting data in R?
- How to deal with error “undefined columns selected when subsetting data frame” in R?
- How to deal with Error: stat_count() can only have an x or y aesthetic in R?
- How to deal with error “Error in shapiro.test(…) : sample size must be between 3 and 5000” in R?
- How to deal with error “var(x) : Calling var(x) on a factor x is defunct.” in R?
- How to deal with NA output of apply in R?
- How to deal with error “Error in eval(predvars, data, env) : numeric 'envir' arg not of length one” in R?
- How to concatenate string vectors separated with hyphen in R?
- How to deal with missing values to calculate correlation matrix in R?
- How to create a matrix with vectors as elements in R?
- How to create combinations for each string values in two vectors in R?

Advertisements