I would like to create an associative array in R from a string like "key1=values1;key2=value2"
. I know this can be done by double splitting and building the array manually but i was wondering if there's already something i can work with.
In PHP, the implode() function is a built-in function that takes an array and converts it to a string. implode() doesn't modify the original array. It doesn't matter whether the array is an indexed or associative array. Once you pass in the array to implode() , it joins all the values to a string.
If the sequential array contains n elements then their index lies between 0 to (n-1). So find the array key value and check if it exist in 0 to (n-1) then it is sequential otherwise associative array.
Associative arrays are used to store key value pairs. For example, to store the marks of different subject of a student in an array, a numerically indexed array would not be the best choice.
$_POST is a predefined variable which is an associative array of key-value pairs passed to a URL by HTTP POST method that uses URLEncoded or multipart/form-data content-type in request.
Using an environment as the "associative array" provides a straightforward 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)
string <- c("key1 = 10, key2 = 20")
eval(parse(text = paste('list(', string, ")")))
$key1
[1] 10
$key2
[1] 20
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With