2011-11-30 109 views
5

我想從像"key1=values1;key2=value2"這樣的字符串在R中創建一個關聯數組。我知道這可以通過雙重分割和手動構建陣列來完成,但我想知道是否已經有一些我可以使用的東西。來自字符串的關聯數組

+0

可能重複的一種方法[R轉換對分成data.frame](http://stackoverflow.com/questions/8127869/r-convert-key -Val-對 - 到 - 數據幀) –

回答

10

使用環境作爲「關聯數組」提供了一個直接的解決方案。

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 
2

下面是使用的eval(parse)

string <- c("key1 = 10, key2 = 20") 
eval(parse(text = paste('list(', string, ")"))) 
$key1 
[1] 10 

$key2 
[1] 20