3 Ways to Fix R Error : $ operator is invalid for atomic vectors

Deepanshu Bhalla Add Comment ,
R has gained popularity among data scientists and statisticians in last few years. Popular R packages are developed after rigorous testing and returns error messages with more explanation which is easy for novice R users to understand them. In base R, one of the most common error encountered is $ operator is invalid for atomic vectors.
Fix R Error : $ operator is invalid for atomic vectors
This error appears when you try to use an element of an atomic vector using the $ operator. Let's call atomic vector as character/numeric vector which most R programmers are familiar with. There are 2 more types of atomic vectors - logical and integer.

Let's understand it via examples. See them below

# Numeric Vector
numVec <- c(3, 2.5, 5.6)

# Character Vector
charVec <- c("Hello", "GroupA")

# Integer Vector
intVec <- c(2L, 4L, 11L)

# Logical Vector
logicalVec <- c(TRUE, FALSE, T, F)

You can check if a vector is an atomic or not by using is.atomic(numVec). It returns TRUE if it is an atomic vector else FALSE.

Let's name the numeric vector using names() function

names(numVec) <- c('A', 'B', 'C')

  A   B   C 
3.0 2.5 5.6 

When we try to access first value by using name A using dollar $ operator, it returns this error.

Error in numVec$A : $ operator is invalid for atomic vectors

There are three ways we can fix this error.


Solution 1 : Use Double Brackets

We can use double brackets [[ ]] to access element by name from an atomic vector. Make sure to use quotes in the name as it is a string.

[1] 3 
Can't we use Single Bracket?
Yes we can use single bracket [ ] for this task but the output will be in a different format. It returns named number instead of just the number. Refer the ouput below.

We can remove name like this unname(numVec['A']). Hence it's better to use double brackets as single bracket complicates things unless you want named number.

Solution 2 : Use getElement( )

getElement( ) follows this syntax style - getElement(object, name). It was designed for this kind of problem statement only.
getElement(numVec, 'A')

[1] 3

Solution 3 : Convert to Dataframe

This is not a recommended solution but the intend is to show you another way to solve this problem using data.frame( ). We need to transpose before wrapping the vector in data.frame( ) as we need data to be stored in a single row with name of vector as column names instead of 3 rows.

myDF <- data.frame(t(numVec))

[1] 3

Related Posts
Spread the Word!
About Author:
Deepanshu Bhalla

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 10 years of experience in data science. During his tenure, he worked with global clients in various domains like Banking, Insurance, Private Equity, Telecom and HR.

Post Comment 0 Response to "3 Ways to Fix R Error : $ operator is invalid for atomic vectors"
Next → ← Prev