Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't R allow $ operator on atomic vectors?

Tags:

r

The following will throw the error "Error in v$a : $ operator is invalid for atomic vectors" (at least in R version 2.14.1):

v <- c(a='a',b='b')
v$a

Apparently, R previously allowed this, which makes me curious as to why.

EDIT: As pointed out below, v$a would have returned NULL in the earlier versions. Changed "fairly recently" to "previously", since I based this on old Internet forums and have been corrected below.

like image 744
Jonathan Avatar asked Mar 22 '12 14:03

Jonathan


People also ask

What operator is used for atomic vectors in R?

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.

How do you fix the operator is invalid for atomic vectors in R?

If you try to use the $ operator to access an element of an atomic vector, you will raise the error $ operator is invalid for atomic vectors. You can solve this error by using single [] or double square brackets [[]] , use the getElement() function, or convert the vector to a Data Frame, then use the $ operator.

Which operator is used for atomic vectors?

Such an error is produced by the R compiler when we try to get an element of an atomic vector by using the $ operator. An atomic vector is simply a 1-dimensional object containing data created with the help of c() and vector() functions.

Is atomic vector in R?

R has six basic ('atomic') vector types: logical, integer, real, complex, string (or character) and raw.


2 Answers

I believe the reason is that the use of v$a vs. v[['a']] is considered less safe.

EDIT: Check out this LINK for more details.

like image 146
Tyler Rinker Avatar answered Sep 19 '22 10:09

Tyler Rinker


Third paragraph of the Details section of ?"$":

‘$’ is only valid for recursive objects, and is only discussed in the section below on recursive objects. Its use on non-recursive objects was deprecated in R 2.5.0 and removed in R 2.7.0.

R-2.7.0 was released in April, 2008. Four years is far from "recent", but maybe you have been a few versions behind for awhile?

like image 43
Joshua Ulrich Avatar answered Sep 22 '22 10:09

Joshua Ulrich