有没有办法用逗号添加引号到列表?

时间:2016-06-03 20:57:15

标签: r

我有一个来自不同来源的长列表,例如:

c(moses, abi, yoyoma) 

我希望将它作为一个对象:

a <- c("moses", "abi", "yoyoma")

有没有办法在不手动为每个名称添加引号的情况下执行此操作?

感谢。

2 个答案:

答案 0 :(得分:2)

快捷方式

cc <- function(...) sapply(substitute(...()), as.character)

cc(moses, abi, yoyoma)
# [1] "moses"  "abi"    "yoyoma"

更灵活的解决方案可能是

cc <- function(..., simplify = TRUE, evaluate = FALSE) {
  l <- eval(substitute(alist(...)))
  ev <- if (evaluate) eval else identity
  sapply(l, function(x) if (is.symbol(x)) as.character(x) else ev(x), simplify = simplify)
}

cc(moses, abi, yoyoma)
# [1] "moses"  "abi"    "yoyoma"


cc(one, two, 'three', four = 4)
#                          four 
# "one"   "two" "three"     "4" 

cc(one, two, 'three something' = rnorm(5), four = 4, simplify = FALSE)
# [[1]]
# [1] "one"
# 
# [[2]]
# [1] "two"
# 
# $`three something`
# rnorm(5)
# 
# $four
# [1] 4

cc(one, two, 'three something' = rnorm(5), four = 4, simplify = FALSE, evaluate = TRUE)
# [[1]]
# [1] "one"
# 
# [[2]]
# [1] "two"
# 
# $`three something`
# [1] -1.1803114  0.3940908 -0.2296465 -0.2818132  1.3744525
# 
# $four
# [1] 4

答案 1 :(得分:1)

只需使用函数as.character()

as.character(a)
 [1] "moses"  "abi"    "yoyoma"
相关问题