How to handle R error: $ operator is invalid for atomic vectors

When encountering the error “$ operator is invalid for atomic vectors” in R, it means that the given task requires a vector (more than one value) to be used, rather than a single value. The $ operator is not valid for atomic vectors, and therefore an appropriate vector should be used in its place.


One common error you may encounter in R is:

$ operator is invalid for atomic vectors

This error occurs when you attempt to access an element of an atomic vector using the $ operator.

An “atomic vector” is any one-dimensional data object created by using the c() or vector() functions in R.

Unfortunately, the $ cannot be used to access elements in atomic vectors. Instead, you must use double brackets [[]] or the getElement() function.

This tutorial shares examples of how to deal with this error in practice.

How to Reproduce the Error Message

Suppose we attempt to use the $ to access an element in the following vector in R:

#define vector
x <- c(1, 3, 7, 6, 2)

#provide names
names(x) <- c('a', 'b', 'c', 'd', 'e')

#display vector
x

a b c d e 
1 3 7 6 2

#attempt to access value in 'e'
x$e

Error in x$e : $ operator is invalid for atomic vectors

We receive an error because it’s not valid to use the $ operator to access elements in atomic vectors. We can also verify that our vector is indeed atomic:

#check if vector is atomic
is.atomic(x)

[1] TRUE

Method #1: Access Elements Using Double Brackets

One way to access elements by name in a vector is to use the [[]] notation:

#define vector
x <- c(1, 3, 7, 6, 2)

#provide names
names(x) <- c('a', 'b', 'c', 'd', 'e')

#access value for 'e'
x[['e']]

[1] 2

Method #2: Access Elements Using getElement()

Another way to access elements by name in a vector is to use the getElement() notation:

#define vector
x <- c(1, 3, 7, 6, 2)

#provide names
names(x) <- c('a', 'b', 'c', 'd', 'e')

#access value for 'e'
getElement(x, 'e')

[1] 2

Method #3 Convert Vector to Data Frame & Use $ Operator

Yet another way to access elements by name in a vector is to first convert the vector to a data frame, then use the $ operator to access the value:

#define vector
x <- c(1, 3, 7, 6, 2)

#provide names
names(x) <- c('a', 'b', 'c', 'd', 'e')

#convert vector to data frame
data_x <- as.data.frame(t(x))

#display data frame
data_x

  a b c d e
1 1 3 7 6 2

#access value for 'e'
data_x$e

[1] 2

The following tutorials explain how to troubleshoot other common errors in R:

How to Fix in R: NAs Introduced by Coercion

x