Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Error in x$ed : $ operator is invalid for atomic vectors

Tags:

r

Here is my code:

x<-c(1,2) x names(x)<- c("bob","ed") x$ed 

Why do I get the following error?

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

like image 824
user3022875 Avatar asked Apr 25 '14 17:04

user3022875


People also ask

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

R doesn't allow us to access elements of an atomic vector using the $ symbol. But we can use double brackets i.e, [[]] or the getElement() function to access them.

How do you find atomic vectors in R?

Atomic vectors are constructed with the c() function or the vector function.

What does atomic vector mean?

vector : An atomic vector is either logical , integer , numeric , complex , character or raw and can have any attributes except a dimension attribute (like matrices). I.e., a factor is an atomic vector, but a matrix or NULL are not. In short, this is basically equivalent to is. atomic(x) && !is.


2 Answers

From the help file about $ (See ?"$") you can read:

$ is only valid for recursive objects, and is only discussed in the section below on recursive objects.

Now, let's check whether x is recursive

> is.recursive(x) [1] FALSE 

A recursive object has a list-like structure. A vector is not recursive, it is an atomic object instead, let's check

> is.atomic(x) [1] TRUE 

Therefore you get an error when applying $ to a vector (non-recursive object), use [ instead:

> x["ed"] ed   2  

You can also use getElement

> getElement(x, "ed") [1] 2 
like image 190
Jilber Urbina Avatar answered Sep 20 '22 10:09

Jilber Urbina


The reason you are getting this error is that you have a vector.

If you want to use the $ operator, you simply need to convert it to a data.frame. But since you only have one row in this particular case, you would also need to transpose it; otherwise bob and ed will become your row names instead of your column names which is what I think you want.

x <- c(1, 2) x names(x) <- c("bob", "ed") x <- as.data.frame(t(x)) x$ed [1] 2 
like image 41
Dalupus Avatar answered Sep 20 '22 10:09

Dalupus