我有一个来自不同来源的长长的列表,例如:
c(moses, abi, yoyoma) 我想把它作为一个对象:
a <- c("moses", "abi", "yoyoma")有没有办法做到这一点,而不手动添加引号到每个名称?
谢谢。
发布于 2016-06-03 21:24:55
快速的方法是
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发布于 2016-06-03 21:14:33
只需使用函数as.character()
as.character(a)
[1] "moses" "abi" "yoyoma"https://stackoverflow.com/questions/37623286
复制相似问题