Reputation: 167
I have a long list from a different source, for example:
c(moses, abi, yoyoma)
I want to have it as an object:
a <- c("moses", "abi", "yoyoma")
Is there a way to do that without manually adding the quotes to each name?
Thanks.
Upvotes: 0
Views: 64
Reputation: 20811
Quick way would be
cc <- function(...) sapply(substitute(...()), as.character)
cc(moses, abi, yoyoma)
# [1] "moses" "abi" "yoyoma"
A more flexible solution might be
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
Upvotes: 2
Reputation: 11
Just use function as.character()
as.character(a)
[1] "moses" "abi" "yoyoma"
Upvotes: 1