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 ofi
.[...]
- Character. The strings in
i
are matched against the names attribute ofx
and the resulting integers are used. For[[
and$
partial matching is used if exact matching fails, sox$aa
will matchx$aabb
ifx
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.
$
is possible with listsv <- list(a=9, b=8, c=7)
. It is not possible to index a vector using$
sign. – Ronak Shahx$aa
aa
is a name, not a vector. so the reference does seem out of place. – MichaelChirico