I want to provide a list of words that are unquoted and convert them into a normal string vector in R. Below is an example of what I would like to do, except for the fact that quote only takes 1 object at a time.
ideally the code below should return TRUE from identical, meaning that the words have been converted to a string vector.
notquotedwords<- quote(Person, Woman, Man, Camera, TV)
#Error in quote(Person, Woman, Man, Camera, TV) :
# 5 arguments passed to 'quote' which requires 1
quotedwords<- c("Person", "Woman", "Man", "Camera", "TV")
identical(notquotedwords, quotedwords)
#ideally the output would be TRUE
This is a MRE, not the actual code, so yes, I understand I could just create a string vector in the first place.
CodePudding user response:
You can get the arguments of a function call with some_call[-1], and match.call will return the parent call by default, so you could do
sym_to_char <- function(...){
as.character(match.call()[-1])
}
notquotedwords <- sym_to_char(Person, Woman, Man, Camera, TV)
quotedwords <- c("Person", "Woman", "Man", "Camera", "TV")
identical(notquotedwords, quotedwords)
#> [1] TRUE
Created on 2022-01-03 by the reprex package (v2.0.1)
With the rlang package, the function ensyms will convert its arguments to symbols.
library(rlang)
sym_to_char <- function(...){
as.character(ensyms(...))
}
notquotedwords <- sym_to_char(Person, Woman, Man, Camera, TV)
quotedwords <- c("Person", "Woman", "Man", "Camera", "TV")
identical(notquotedwords, quotedwords)
#> [1] TRUE
Created on 2022-01-03 by the reprex package (v2.0.1)
CodePudding user response:
To do this you need the quos and quo_name function from rlang
library(rlang)
notquotedwords<- quos(Person, Woman, Man, Camera, TV)
notquotedwords_char <- as.character(unlist(lapply(notquotedwords, quo_name)))
all.equal(notquotedwords_char , quotedwords)
