2012-05-16 26 views
12

我有R中的列表:追加到动态名称的列表,R

a <- list(n1 = "hi", n2 = "hello") 

我想附加到这个命名为名单,但名称必须是动态的。也就是说,他们是从一个字符串创建(例如:paste("another","name",sep="_")

我试着这样做不工作:

c(a, parse(text="paste(\"another\",\"name\",sep=\"_\")=\"hola\"") 

什么是做到这一点的正确方法的最终目标就是要追加该列表,动态地选择我的名字。

回答

19

你可以只使用索引用双括号。无论下面的方法应该工作。

a <- list(n1 = "hi", n2 = "hello") 
val <- "another name" 
a[[val]] <- "hola" 
a 
#$n1 
#[1] "hi" 
# 
#$n2 
#[1] "hello" 
# 
#$`another name` 
#[1] "hola" 

a[[paste("blah", "ok", sep = "_")]] <- "hey" 
a 
#$n1 
#[1] "hi" 
# 
#$n2 
#[1] "hello" 
# 
#$`another name` 
#[1] "hola" 
# 
#$blah_ok 
#[1] "hey" 
+0

谢谢你,非常简短,点解 – Alex

9

您可以使用setNames设置在飞行的名字:

a <- list(n1 = "hi", n2 = "hello") 
c(a,setNames(list("hola"),paste("another","name",sep="_"))) 

结果:

$n1 
[1] "hi" 

$n2 
[1] "hello" 

$another_name 
[1] "hola" 
+0

谢谢你,这是伟大的。很高兴知道setNames。 – Alex