In R language, you get the error, “$ operator is invalid for atomic vectors” when you try to apply $
to a non-recursive object. As in the R language documentation –
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. That is, the index is not computable: for cases where you need to evaluate an expression to find the index, usex[[expr]]
. Applying$
to a non-recursive object is an error.
So, for atomic vectors, you should use x[i]
notation. Check this code –
> x <- rnorm(5) > x [1] -0.12526937 -0.27961154 -1.03718717 -0.08156527 1.37167090 > x[2] [1] -0.2796115
If it’s a list, then you can use x$a
or x[[i]]
notation. Check the code below –
> x <- list("Red", "Green", c(21,32,11), TRUE, 51.23, 119.1) > x[[2]] [1] Green > names(x) <- c("red_color", "green_color", "vector_", "bool_", "float_51_23", "fload_119_1") > x$`green_color` [1] Green
Check if vector is atomic or recursive
If you have doubts whether your declared vector is atomic or recursive, you can use is.recursive(x)
and is.atomic(x)
–
> x <- rnorm(5) > is.recursive(x) [1] FALSE > is.atomic(x) [1] TRUE
Convert vector to list
You can also convert a vector to the list using as.list(x)
command. This way you will be able to use x$a
notation for your atomic vector. Check this code –
> x <- c(1, 2) x > names(x) <- c("bob", "ed") > x <- as.list(t(x)) > x$ed [1] 2
There are number of operators in R which could come in handy for you –
- |
Minus, can be unary or binary |
+ |
Plus, can be unary or binary |
! |
Unary not |
~ |
Tilde, used for model formulae, can be either unary or binary |
? |
Help |
: |
Sequence, binary (in model formulae: interaction) |
* |
Multiplication, binary |
/ |
Division, binary |
^ |
Exponentiation, binary |
%x% |
Special binary operators, x can be replaced by any valid name |
%% |
Modulus, binary |
%/% |
Integer divide, binary |
%*% |
Matrix product, binary |
%o% |
Outer product, binary |
%x% |
Kronecker product, binary |
%in% |
Matching operator, binary (in model formulae: nesting) |
< |
Less than, binary |
> |
Greater than, binary |
== |
Equal to, binary |
>= |
Greater than or equal to, binary |
<= |
Less than or equal to, binary |
& |
And, binary, vectorized |
&& |
And, binary, not vectorized |
| |
Or, binary, vectorized |
|| |
Or, binary, not vectorized |
<- |
Left assignment, binary |
-> |
Right assignment, binary |
$ |
List subset, binary |