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

Time:01-30

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.

CodePudding user response:

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)

CodePudding user response:

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))
  •  Tags:  
  • Related