在R中将非引用词列表转换为字符向量

6
我想提供一个单词列表,将其转换为R中的普通字符串向量,并且不要加上引号。下面是一个示例,除了 quote 只能一次处理一个对象之外,我希望得到相同的结果。

理想情况下,下面的代码应该返回 TRUE,表示这些单词已经被转换成了字符串向量。
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

这是一个 MRE,而不是实际代码,所以我理解我可以一开始就创建一个字符串向量。


1
你在引用一个单词向量吗?例如 quote(c(Person, Woman, Man, Camera, TV)) - Onyambu
3个回答

7
您可以使用some_call[-1]获取函数调用的参数,match.call默认会返回父级调用,所以您可以这样做:
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

该内容由reprex软件包 (v2.0.1)于2022年1月3日创建

使用rlang软件包,函数ensyms将其参数转换为符号。

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

本示例由 reprex 包 (v2.0.1) 于2022-01-03创建。


为什么要使用sapplyas.character是向量化的。因此,as.character(match.call()[-1])应该可以工作。 - Onyambu
感谢 @Onyambu。没有什么好的理由,只是我在早期版本中使用了 rlang::as_string,而它不能以这种方式使用。 - IceCreamToucan

2
为了做到这一点,您需要从rlang中使用quosquo_name函数。
library(rlang)
notquotedwords<- quos(Person, Woman, Man, Camera, TV)
notquotedwords_char <- as.character(unlist(lapply(notquotedwords, quo_name)))
all.equal(notquotedwords_char , quotedwords)

1
< p > substitute 的一个未记录的特性可以在这里使用:

f = function(...) as.character(substitute(...()))

identical(
  c("Person", "Woman", "Man", "Camera", "TV"),
  f(Person, Woman, Man, Camera, TV)
)
[1] TRUE

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接