The R error "$ operator is invalid for atomic vectors in R" occurs when you try to access an element of an atomic vector using the \$
operator. To solve this, use double brackets [[]]
, the getElement()
function, or convert the vector to a data.frame
and use $
.
An atomic vector
is a 1-dimensional data object created from the c()
or vector()
functions. $
cannot be used to access elements in atomic vectors. $
can only be used for recursive objects. Vectors are atomic objects.
The solution is to use double brackets [[]]
or the getElement()
function.
Here is an example of how the error occurs.
# 👇️ define the vector
example <- c(6, 3, 8, 6, 2)
# provide names
names(example) <- c('a', 'b', 'c', 'd', 'e')
# display vector
example
>> a b c d e
6 3 8 6 2
# ⛔️ Error: $ operator is invalid for atomic vectors in R
# attempt to access value in 'c'
example$c
The error occurs because we cannot use the $
operator to access elements in atomic vectors. $
can only be used for recursive objects.
We can check the the vector is in fact atomic and not recursive.
# 🔎 check if the vector is atomic
is.atomic(example)
# 🔎 check if the vector is recursive
is.recursive(example)
>> FALSE
[[]]
To solve this, we can access the elements in a vector by their name using the [[]]
notation.
# 👇️ define the vector
example <- c(6, 3, 8, 6, 2)
# provide names
names(example) <- c('a', 'b', 'c', 'd', 'e')
# access value for 'c' using double brackets
example[['c']]
>> 8
getElement()
Another method is to use the getElement()
function.
# 👇️ define the vector
example <- c(6, 3, 8, 6, 2)
# provide names
names(example) <- c('a', 'b', 'c', 'd', 'e')
# access value for 'c' using double brackets
getElement(example, 'c')
>> 8
data frame
and use $
A third way is to convert the vector
into a data frame
, and use the $
operator to access the elements by name.
# 👇️ define the vector
example <- c(6, 3, 8, 6, 2)
# provide names
names(example) <- c('a', 'b', 'c', 'd', 'e')
# convert the vector to a data frame
data_example <- as.data.frame(t(example))
# display the data frame
data_example
>> a b c d e
6 3 8 6 2
# access value for 'c' using $
data_example$c
>> 8
The R error "$ operator is invalid for atomic vectors in R" occurs when you try to access an element of an atomic vector using the \$
operator. To solve this, use double brackets [[]]
, the getElement()
function, or convert the vector to a data.frame
and use $
.
Related tutorials curated for you
Error in file(file, "rt") : cannot open the connection
Non-numeric argument to binary operator error in R
$ operator is invalid for atomic vectors in R
Error in plot.new() : figure margins too large
R: the condition has length > 1 and only the first element will be used