Question

Environments in R behave similar to list. Would the following code snippet work?

#using pkg rlang to create environment

env = rlang::env(
  'a' = 1,
  'b' = 1:10,
  'c' = list(1,'x', 2)
)

env[[1]]

Answer

Calling the objects of environment using index will not work as the names (of objects) in environment are unordered. It will throw a subsetting error.

env = rlang::env(
  'a' = 1,
  'b' = 1:10,
  'c' = list(1,'x', 2)
)

env[[1]]
## Error in env[[1]]: wrong arguments for subsetting an environment

Use names to call out objects. For example:

env = rlang::env(
  'a' = 1,
  'b' = 1:10,
  'c' = list(1,'x', 2)
)

env[['a']] #or env$a
## [1] 1

Reference: Advanced R by Hadley Wickham

Thanks for reading. If you like the question, how about some love and coffee: Buy me a coffee