\$ operator is invalid for atomic vectors – R Error

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)

Get only the best articles delivered to your mail

Warning: the condition has length > 1 and only the first element will be used

R-lang throws the warning, the condition has length > 1 and only the first element will be used because if statement is not vectorized. In it’s place you need to…

R lang – Remove rows in dataframe

R lang provides the – operator to remove rows from dataframe. Simply provide the indexes of rows to remove with – sign. Consider this example – Here we have created…

error in file(file, “rt”) : cannot open the connection

R throws error in file(file, “rt”) : cannot open the connection, when it’s not able to find the file in the provided path. This could happen either due to wrong…

(list) object cannot be coerced to type ‘double’ – R Error

R-language throws error (list) object cannot be coerced to type ‘double‘ when we try to convert a list of string or other type values to a numeric vector. To correctly…

%% in r language

%% in r language gives the modulus of two numbers. It is basically the remainder of division of first number by second number. Consider this code – Here we are…