R, When does the error "$operator is invalid for atomic vectors" occur? Jesmin New Member Code: pmf <- array(c(2/15,1/15,4/15,1/15,3/15,4/15),dim=c(2,3), dimnames=list(X=1:2,Y=1:3)) pmf$Y
Error in pmf$Y :$ operator is invalid for atomic vectors
please give detail explanation. I have faced the problem a number of times not only for 'array' but also for 'data.frame'.

Jesmin

New Member
what exactly do you expect pmf$Y to return? Rather i give another example: Code: b <- matrix(1:6,nrow=2,dimnames=list(c("X1","X2"),c("Y1","Y2","Y3"))) b b$X1
or

Code:
pmf <- array(c(2/15,1/15,4/15,1/15,3/15,4/15),dim=c(2,3),
dimnames=list(X=1:2,Y=1:3))
seq_along(pmf$Y) Error in pmf$Y : $operator is invalid for atomic vectors I actually expect 1 2 3 from seq_along(pmf$Y)

Last edited:

trinker

ggplot2orBust
I don't index arrays but it's much safer to index a matrix with the square brakets as seen below:

Code:
b <- matrix(1:6,nrow=2,dimnames=list(c("X1","X2"),c("Y1","Y2","Y3")))
b
b["X1", ]

bryangoodrich

Probably A Mammal
vector, matrix, and arrays are all of a vector type. Technically lists are on the face of them, but they're vectors of hashes (names) to list elements. A data.frame is just a special kind of list (a list with atomic vectors of equal length). Though, that doesn't have to be the case (you can have a data.frame with a 'table cell' that contains a vector or something complex itself, but you should avoid that!

In any case, LISTS data structures in R can use the "$" operator. That is built into R. It is NOT available for vector data structure. You have to use dimension indexing with square brackets. The brackets are more general and apply to data.frames because frames are intended to be "like" matrix in form (tabular/columnar). However, underneath, a frame is still just a special kind of lists. Lists can use the "$" operator because it is expected to be a hash, which means the value of a list element is determined by its key. Unlike hashables in other programming languages, R lists can still be accessed by numeric index, which is why you can do something like MyList[[4]] to access the 4th element of a list. This is also why I said lists are still vectors at some level because they are stored with indexes (either that or behind the scenes the keys are kept in a vector, but who knows).

Therefore, your trying to access named dimensions of vectors, matrices, or arrays using the "\$" operator will fail. A vector is generic and is single dimensional. A matrix is a 2D vector. An array is any higher dimensional vector. You can access named components only through dimensions which is only accessible through dimensional indexing (brackets) as Trinker showed.