0
votes

Characters can be used to index a named vector in the following way:

v <- c(a=9, b=8, c=7)
v[["a"]]  # Returns: 9

I am reading the R Language Definition, § 3.4.1 Indexing by vectors, which seems to say that the dollar sign ($) can be used to access the contents of a named vector:

R allows some powerful constructions using vectors as indices. We shall discuss indexing of simple vectors first. For simplicity, assume that the expression is x[i]. Then the following possibilities exist according to the type of i.

[...]

  • Character. The strings in i are matched against the names attribute of x and the resulting integers are used. For [[ and $ partial matching is used if exact matching fails, so x$aa will match x$aabb if x does not contain a component named "aa" and "aabb" is the only name which has prefix "aa". [...]

So I tried to use $ in the following way:

v <- c(a=9, b=8, c=7)
v$a

However, I get an error:

Error in v$a : $ operator is invalid for atomic vectors

What does this mean? I must be misunderstanding the excerpt from the R Language Definition above.

1
Indexing using $ is possible with lists v <- list(a=9, b=8, c=7). It is not possible to index a vector using $ sign.Ronak Shah
@RonakShah If that's the case, then why does the text say "We shall discuss indexing of simple vectors first"?Flux
the main thrust of that section is talking about x[i] usages, it's a bit odd for mention of $ to happen off-handedly there. the behavior of $ described there applies where $ does, which is not for atomic vectors (as (often) constructed by c() (see ?is.atomic for details) and mentioned in your error message). the behavior described would apply to lists and I believe environments, e.g.MichaelChirico
The focus of that section is on indexing by vectors. It is not mentioned that we are indexing vectors, lists or anything else.Ronak Shah
@RonakShah but in x$aa aa is a name, not a vector. so the reference does seem out of place.MichaelChirico

1 Answers

0
votes

In the introductory part of section 3.4 indexing, whose first subsection is the paragraph that you mentioned (3.4.1 Indexing by vectors), it is specified that:

The form using $ applies to recursive objects such as lists and pairlists. It allows only a literal character string or a symbol as the index.

Applying $ to a non-recursive object is an error."

In your example, you are indexing a non-recursive object using $. And because the vector being indexed is not recursive, you got an error.

You can test if an object is recursive using the function is.recursive. Note that an environment object is also recursive.

v <- c(a=9, b=8, c=7)
x <- list(a=8, b=3)
y <- pairlist(a=5)
e <- as.environment(x)

is.recursive(v)
# [1] FALSE
is.recursive(x)
# [1] TRUE
is.recursive(y)
# [1] TRUE
is.recursive(e)
# [1] TRUE