使用字符值作为对象名称

时间:2012-02-19 20:32:49

标签: r vector

我想使用向量中的字符作为字符对象的名称 旨在获得

first as say "d","e","a","t" etc.

尝试了这种方法,但显然缺少一些适用于x [i]

的功能
x <- c("first","second","third"..)

for (i in 1:length(x)) {
x[i] <- sample(letters,4)
}

TIA

2 个答案:

答案 0 :(得分:2)

您正在寻找的功能是assign()

> x <- c("first","second","third")
> for (i in 1:length(x)) {
+ assign(x[i], sample(letters,4))
+ }
> 
> ls()
[1] "first"  "i"      "second" "third"  "x"     
> first
[1] "t" "d" "u" "j"
> second
[1] "o" "i" "p" "l"
> third
[1] "w" "v" "r" "n"

作为替代方案,您可以将这些向量构建为列表的不同元素:

> mylist <- list()
> for (i in 1:length(x)) {
+ mylist[[x[i]]] <- sample(letters,4)
+ }
> mylist
$first
[1] "e" "l" "y" "d"

$second
[1] "t" "o" "k" "h"

$third
[1] "g" "x" "p" "b"

答案 1 :(得分:1)

您没有说明您将使用此对象做什么。您可以通过使用命名向量来获得最简单的结构:

names(x) <- x
x[] <- sample(letters, 4)

如果您不使用LHS上的配对括号,则会替换整个矢量并且名称将丢失。您现在可以使用带引号的名称访问值:

> x
 first second  third fourth 
   "w"    "c"    "r"    "x" 
> x["second"]
second 
   "c"