我想提供一個未加引號的單詞串列,并將它們轉換為 R 中的普通字串向量。下面是我想要做的一個例子,除了quote一次只需要 1 個物件的事實。
理想情況下,下面的代碼應該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,而不是實際的代碼,所以是的,我知道我可以首先創建一個字串向量。
uj5u.com熱心網友回復:
你可以用一個函式呼叫的引數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 年 1 月 3 日創建
uj5u.com熱心網友回復:
要做到這一點,你需要的quos,并quo_name從功能rlang
library(rlang)
notquotedwords<- quos(Person, Woman, Man, Camera, TV)
notquotedwords_char <- as.character(unlist(lapply(notquotedwords, quo_name)))
all.equal(notquotedwords_char , quotedwords)
uj5u.com熱心網友回復:
substitute可以在此處使用未記錄的功能:
f = function(...) as.character(substitute(...()))
identical(
c("Person", "Woman", "Man", "Camera", "TV"),
f(Person, Woman, Man, Camera, TV)
)
[1] TRUE
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/403227.html
標籤:
上一篇:在基于actionButton()和ShinyJS()的模塊化閃亮應用程式中顯示和隱藏文本
下一篇:使用剪切和中斷將日期分組為周
