2
我想用中的字符,矢量字符的名稱的對象 目標是獲得使用字符值作爲對象名稱
first as say "d","e","a","t" etc.
嘗試過這種方法,但很顯然缺少一些功能,以適用於X [我]
x <- c("first","second","third"..)
for (i in 1:length(x)) {
x[i] <- sample(letters,4)
}
TIA
我想用中的字符,矢量字符的名稱的對象 目標是獲得使用字符值作爲對象名稱
first as say "d","e","a","t" etc.
嘗試過這種方法,但很顯然缺少一些功能,以適用於X [我]
x <- c("first","second","third"..)
for (i in 1:length(x)) {
x[i] <- sample(letters,4)
}
TIA
你正在尋找的功能是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"
你不說你會對此對象做什麼。您可以通過使用一個名爲向量得到最簡單的結構:
names(x) <- x
x[] <- sample(letters, 4)
如果你不使用的LHS配對支架,整個矢量被替換和名稱都將丟失。您現在可以使用帶引號的名稱訪問這些值:
> x
first second third fourth
"w" "c" "r" "x"
> x["second"]
second
"c"