问题

我正在尝试编写一个使命名矢量如下的函数:

 > x
  a   b   c 
"i" "j" "k" 
 

但以下功能:

 getNamedCharacter <- function() {
  x[c("a", "b", "c")] <- c("i", "j", "k")
}
 

...返回无名的矢量:

 > x <- getNamedCharacter()
> x
[1] 1 2 3
 

....代码行本身按预期工作:

 > x <- NULL
> x[c("a", "b", "c")] <- c("i", "j", "k")
> x
  a   b   c 
"i" "j" "k"
 

如何使用函数获取名称向量? 谢谢!

  最佳答案

我们可以使用structure.也可能添加属性:

 make_named_vec <- function(vec, vec_names){
  structure(vec, names = vec_names)
 }
 make_named_vec(c("i","j","k"), c("a","b","c"))
  a   b   c 
"i" "j" "k"

res <-make_named_vec(c("i","j","k"), c("a","b","c"))
 str(res)
 Named chr [1:3] "i" "j" "k"
 - attr(*, "names")= chr [1:3] "a" "b" "c"
 

  相同标签的其他问题

r