1

Consider

ex1 = quote(fn(NULL))

and suppose I wish to make ex1 equals to fn(lhs=rhs) in expression form, how do I do that?

since

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

gives ex1 = fn((lhs=rhs)) and I can't seem to get rid of the parenthesis.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
xiaodai
  • 14,889
  • 18
  • 76
  • 140

2 Answers2

2

1) as.call Create a list formed from the function name and the arguments in name = value form and then use as.call to convert that to a call object.

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

In a comment @Allan Cameron suggested this variation:

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

2) call Another way is to use call. It requires a character string for the function name so use deparse to get that.

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

3) character Another approach is to create a character string representing the call and then convert that back to a call object. Here parse creates an expression such that its first component is a call object.

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

Note

Input is:

ex1 <- quote(fn(NULL))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
1

You can do

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

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

Created on 2022-01-29 by the reprex package (v2.0.1)

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87