How to convert vector like c("x","y","z")
to function(x , y, z){}
in R?
I am looking for something like reverse function of formalArgs()
.
Note that, I know about as.function(alist(x=,y=,{}))
but I don't know how to insert x=
and y=
in it from a given vector.
Basically to get this to work you need to call
as.function(alist(x=, y=, z=, {}))`
which is equivalent to
as.function(alist(x=bquote(), y=bquote(), z=bquote(), {}))
The second form is nice because we have a set of named arguments to alist
, which can provide programmatically using a list and do.call
:
l <- list(x=bquote(), y=bquote(), z=bquote(), bquote({}))
as.function(do.call(alist, l))
# function (x, y, z)
# {
# }
All that remains is to construct our list l
programmatically from the list of variable names, which can be done with setNames
and replicate
:
vec <- c("x","y","z")
as.function(do.call(alist, c(setNames(replicate(length(vec), bquote(), F), vec),
bquote({}))))
# function (x, y, z)
# {
# }
The arguments are just a named list. The coercion to the internal pairlist is automatic.
#argument list
p<-c("x","y","z")
args<-vector("list",length(p))
for(i in seq(args)) args[[i]]<-substitute()
names(args)<-p
#set a default value for y for the sake of example
args$y<-2
#construct function
body<-quote(x+y+z)
f<-as.function(c(args,body))
#test it
f(1,z=3)
#[1] 6
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.