R Error in x$ed : $ operator is invalid for atomic vectors
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
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)  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)  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")  2
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  2
Because $ does not work on atomic vectors. Use [ or [[ instead. From the help file for $:
The default methods work somewhat differently for atomic vectors, matrices/arrays and for recursive (list-like, see is.recursive) objects. $ is only valid for recursive objects, and is only discussed in the section below on recursive objects.
x[["ed"]] will work.
You get this error, despite everything being in line, because of a conflict caused by one of the packages that are currently loaded in your R environment.
So, to solve this issue, detach all the packages that are not needed from the R environment. For example, when I had the same issue, I did the following:
bottom line: detach all the libraries no longer needed for execution... and the problem will be solved.
Here x is a vector. You need to convert it into a dataframe for using $ operator.
x <- as.data.frame(x)
will work for you.
x<-c(1,2) names(x)<- c("bob","ed") x <- as.data.frame(x)
will give you output of x as: bob 1 ed 2 And, will give you output of x$ed as: NULL If you want bob and ed as column names then you need to transpose the dataframe like x <- as.data.frame(t(x)) So your code becomes
x<-c(1,2) x names(x)<- c("bob","ed") x$ed x <- as.data.frame(t(x))
Now the output of x$ed is:  2
Atomic collections are accessible by $
Recursive collections are not. Rather the [[ ]] is used
Browse> is.atomic(list())  FALSE Browse> is.atomic(data.frame())  FALSE Browse> is.atomic(class(list(foo="bar")))  TRUE Browse> is.atomic(c(" lang "))  TRUE
R can be funny sometimes
a = list(1,2,3) b = data.frame(a) d = rbind("?",c(b)) e = exp(1) f = list(d) print(data.frame(c(list(f,e)))) X1 X2 X3 X2.71828182845905 1 ? ? ? 2.718282 2 1 2 3 2.718282