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

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 –

## Live Demo

Live demo might not work in Private Window (Incognito)

Tagged in:

,