如何从字符串创建带引号的表达式

Ric*_*rta 12 expression r quote data.table

给定一个字符串向量,我想创建一个没有引号的表达式.

# eg, I would like to go from 
c("string1", "string2")

# to...  (notice the lack of '"' marks)
quote(list(string1, string2))
Run Code Online (Sandbox Code Playgroud)

我在删除引号时遇到了一些困难

input <- c("string1", "string2")
output <- paste0("quote(list(", paste(input, collapse=","), "))")

# not quite what I am looking for.     
as.expression(output)
expression("quote(list(string1,string2))")
Run Code Online (Sandbox Code Playgroud)



这用于data.table列选择,如果相关的话.
我正在寻找的应该能够适应data.table如下:

library(data.table)
mydt <- data.table(id=1:3, string1=LETTERS[1:3], string2=letters[1:3])

result <- ????? # some.function.of(input)
> mydt[ , eval( result )]
   string1 string2
1:       A       a
2:       B       b
3:       C       c
Run Code Online (Sandbox Code Playgroud)

Jos*_*ien 11

这是我要做的:

## Create an example of a data.table "dt" whose columns you want to index 
## using a character vector "xx"
library(data.table)
dt <- data.table(mtcars)
xx <- c("wt", "mpg")

## Construct a call object identical to that produced by quote(list("wt", "mpg"))
jj <- as.call(lapply(c("list", xx), as.symbol))

## Try it out
dt[1:5,eval(jj)]
#       wt  mpg
# 1: 2.620 21.0
# 2: 2.875 21.0
# 3: 2.320 22.8
# 4: 3.215 21.4
# 5: 3.440 18.7
Run Code Online (Sandbox Code Playgroud)

当像这样"计算语言"时,看看你想要构建的对象的结构通常会有所帮助.基于以下内容(一旦您了解as.call()as.symbol()),创建所需的语言对象就变得轻而易举:

x <- quote(list(wt, mpg))

str(x)
#  language list(wt, mpg)

class(x)
# [1] "call"

str(as.list(x))
# List of 3
#  $ : symbol list
#  $ : symbol wt
#  $ : symbol mpg
Run Code Online (Sandbox Code Playgroud)


mne*_*nel 5

我倾向于使用as.quotedplyr包

 outputString <- sprintf('list(%s)', paste(input, collapse = ', ')) 


 library(plyr)
  output <- as.quoted(outputString)[[1]]

  mydt[, eval(output)]
   string1 string2
1:       A       a
2:       B       b
3:       C       c
Run Code Online (Sandbox Code Playgroud)

但是,如果只是列选择,则可以传递字符串并使用 ..

mydt[ , ..input]
   string1 string2
1:       A       a
2:       B       b
3:       C       c
Run Code Online (Sandbox Code Playgroud)