给定 `fn(NULL)` 形式的表达式,我如何用 `lhs=rhs` 替换空值?

Given an expression of the form `fn(NULL)` how do I replace the null with `lhs=rhs`?

考虑

ex1 = quote(fn(NULL))

假设我想让 ex1 等于表达式形式的 fn(lhs=rhs),我该怎么做?

ex1[[2]] = quote(lhs=rhs)

给出 ex1 = fn((lhs=rhs)) 我似乎无法摆脱括号。

你可以做到

ex1 <- quote(fn(NULL))
ex1
#> fn(NULL)

ex1[[2]] <- quote(rhs)
names(ex1)[2] <- "lhs"
ex1
#> fn(lhs = rhs)

reprex package (v2.0.1)

于 2022-01-29 创建

1) as.call 创建一个由函数名和 name = value 形式的参数组成的列表,然后使用 as.call 将其转换为调用对象。

as.call(list(ex1[[1]], lhs = quote(rhs)))
## fn(lhs = rhs)

@Allan Cameron 在评论中提出了这种变化:

as.call(c(ex1[[1]], alist(lhs = rhs)))

2)调用另一种方法是使用call。它需要一个字符串作为函数名称,因此使用 deparse 来获取它。

call(deparse(ex1[[1]]), lhs = quote(rhs))
## fn(lhs = rhs)

3) character 另一种方法是创建一个表示调用的字符串,然后将其转换回调用对象。这里 parse 创建一个表达式,其第一个组件是调用对象。

parse(text = sprintf("%s(%s)", deparse(ex1[[1]]), "lhs = rhs"))[[1]]
## fn(lhs = rhs)

备注

输入为:

ex1 <- quote(fn(NULL))