【问题标题】:Parse a string in place of expression argument解析字符串代替表达式参数
【发布时间】:2015-03-19 19:08:45
【问题描述】:

我想将表达式作为参数发送到 rlist 包中的函数 list.select

函数list.select的正常使用如下:

x <- list(p1 = list(type='A',score=list(c1=10,c2=8)), p2 = list(type='B',score=list(c1=9,c2=9)), p3 = list(type='B',score=list(c1=9,c2=7)))
list.select(x, type)

type 是所选列表元素的名称。我想通过使其成为从字符串解析的表达式来参数化列表元素的名称。

list.select(x, parse(text='type'))

但这不起作用。以下是两个函数调用的结果:

> list.select(x, type)
$p1
$p1$type
[1] "A"
$p2
$p2$type
[1] "B"
$p3
$p3$type
[1] "B"
> list.select(x, parse(text='type'))
$p1
$p1[[1]]
expression(type)
$p2
$p2[[1]]
expression(type)
$p3
$p3[[1]]
expression(type)

如何使用字符串代替表达式?

【问题讨论】:

    标签: r metaprogramming


    【解决方案1】:

    list.select 进行非标准评估,因此您需要为其构造调用。这是一个例子:

    tag.name <- "type"
    eval(call("list.select", x, as.name(tag.name)))
    

    生产:

    $p1
    $p1$type
    [1] "A"
    
    
    $p2
    $p2$type
    [1] "B"
    
    
    $p3
    $p3$type
    [1] "B"
    

    我所做的和你所做的区别在于我构建了整个调用以避免给list.select 一个错误解释其参数的机会。您的版本首先评估 list.select,从那时起,您将受制于 list.select 想要如何解释其参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-29
      • 2015-06-20
      • 2012-08-07
      相关资源
      最近更新 更多