如何从字符串创建带引号的表达式 [英] how to create a quoted expression from strings
本文介绍了如何从字符串创建带引号的表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个字符串向量,我想创建一个没有引号的表达式。
Given a vector of strings, I would like to create an expression without the quotation marks.
# eg, I would like to go from
c("string1", "string2")
# to... (notice the lack of '"' marks)
quote(list(string1, string2))
我遇到一些困难删除引号
I am encountering some difficulty dropping the quotation marks
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))")
这是用于data.table列选择,
我要查找的内容应该能够适合data.table如下:
This is for use in data.table column selection, in case relevant.
What I am looking for should be able to fit into data.table as follows:
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
推荐答案
这里是我要做的:
## 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
计算语言,这样常常有助于看看结构你试图构造的对象。基于以下内容(一旦你知道 as.call()
和 as.symbol()
),所需的语言对象变成一块蛋糕:
When "computing on the language" like this, it's often helpful to have a look at the structure of the object you're trying to construct. Based on the following (and once you know about as.call()
and as.symbol()
), creating the desired language object becomes a piece of cake:
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
这篇关于如何从字符串创建带引号的表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文