I would like to create an associative array in R from a type string "key1=values1;key2=value2". I know that this can be done by double splitting and building the array manually, but I was wondering if I have something that I can work with.
"key1=values1;key2=value2"
Using the environment as an "associative array" provides a simple solution.
string <- "key1=99; key2=6" # Create an environment which will be your array env <- new.env() # Assign values to keys in the environment, using eval(parse()) eval(parse(text=string), envir=env) # Check that it works: ls(env) # [1] "key1" "key2" env$key1 # [1] 99 as.list(env) # $key1 # [1] 99 # $key2 # [1] 6
Here is one approach using eval(parse)
eval(parse)
string <- c("key1 = 10, key2 = 20") eval(parse(text = paste('list(', string, ")"))) $key1 [1] 10 $key2 [1] 20