【问题标题】:change names in dots to characters将点中的名称更改为字符
【发布时间】:2018-04-27 17:27:08
【问题描述】:

我有一个这样的功能:

my_fun <- function(...,x,y){
  list(...)
}

我希望能够将变量名或字符串提供给省略号,并在返回之前将全部转换为字符。在我的真实案例中,我将通过do.call(custom_fun,list(...)) 调用自定义函数。

预期输出

我在这里要问的是一个函数my_fun2,它将具有以下行为:

my_fun2 <- function(...,x,y){
  MAGIC(list(...))
}

identical(my_fun("a",foo= "b == 3",c("c","d"),bar=c("e","f"),c("g","h")),
          my_fun2("a",foo= b == 3,c("c","d"),bar = c("e",f),c(g,h)))

应该是 TRUE 并且两个词都返回:

# [[1]]
# [1] "a"
# 
# $foo
# [1] "b == 3"
# 
# [[3]]
# [1] "c" "d"
# 
# $bar
# [1] "e" "f"
# 
# [[5]]
# [1] "g" "h"

我尝试了什么...

my_fun2 <- function(...,x,y){
 lapply(pryr::dots(...),as.character)
}

my_fun2("a",b == 3,c("c","d"),c("e",f),c(g,h))
# [[1]]
# [1] "a"
# 
# [[2]]
# [1] "==" "b"  "3" 
# 
# [[3]]
# [1] "c" "c" "d"
# 
# [[4]]
# [1] "c" "e" "f"
# 
# [[5]]
# [1] "c" "g" "h"

备注

我对表达、引语、引语、称呼、名字没有很好的理解。所以我会感谢与案例相关的解释。

我可以使用basesubstitutequote 等)和dplyr 答案(enquoquosetc)中的任何一个(或两者!)的解决方案

【问题讨论】:

  • as.character(substitute(alist(...)))[-1] 呢?
  • as.character(substitute(alist(...)))[-1] 返回[1] "a" "b" "c(\"c\", \"d\")" "c(\"e\", f)" "c(g, h)",它与向量混淆。
  • 如果您还没有看过它,这可能会有所帮助:adv-r.had.co.nz/Computing-on-the-language.html#capturing-dots
  • 我认为sapply(substitute(alist(...)),as.character) 在我用b ==3 概括我的问题之前会起作用,它给了我[1] "==" "b" "3" 用于我的第三个元素而不是保持元素有序(并粘贴在一起),一些与我假设的表达式的解析有关

标签: r names ellipsis


【解决方案1】:

我并不骄傲,但这是必须要做的......

library(dplyr)
library(purrr)
library(pryr)
my_fun2 <- function(...,x,y){
  dots0 <- as.character(substitute(alist(...)))[-1]
  vectors <- substr(dots0,1,2) == "c("
  dotsv <- dots0[vectors] %>%
    gsub("\"","",.)    %>% 
    gsub("(","('",.,fixed=TRUE)   %>% 
    gsub(", ","', '",.,fixed=TRUE)  %>%
    gsub(")","')",.,fixed=TRUE)  %>%
    map(~eval(parse(text=.x)))
  setNames(c(as.list(dots0[!vectors]),dotsv),names(pryr::dots(...)))
}

identical(my_fun2("a",foo= "b == 3",c("c","d"),bar = c("e","f"),c("g","h")),
my_fun2("a",foo= b == 3,c("c","d"),bar = c("e",f),c(g,h)))
# [1] TRUE

# [[1]]
# [1] "a"
# 
# $foo
# [1] "b == 3"
# 
# [[3]]
# [1] "c" "d"
# 
# $bar
# [1] "e" "f"
# 
# [[5]]
# [1] "g" "h"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 2017-05-29
    • 1970-01-01
    相关资源
    最近更新 更多