Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associative array from string

Tags:

text

r

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.

like image 368
raygozag Avatar asked Nov 30 '11 20:11

raygozag


People also ask

How do you convert associative array to string?

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.

How do you find an associative array?

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.

What is associative array with example?

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.

Is $_ POST an associative array?

$_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.


2 Answers

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
like image 115
Josh O'Brien Avatar answered Sep 28 '22 05:09

Josh O'Brien


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
like image 37
Ramnath Avatar answered Sep 28 '22 05:09

Ramnath