How do I call a 'call' object in R

Viewed 36

I have a function that returns, among other things, a call generated by match.call() that in this case returns

build_model.kd_data(data = kd_data, optimizer = optimizer_rmsprop(), loss = loss_poisson)

How do I then call that again, effectively repeating the entire function again?

1 Answers

You use eval to evaluate a call.

Although eval is sometimes abused via the usually inappropriate eval(parse(...)) idiom, it is perfectly reasonable to use it on a call captured by match.call or constructed through the call or as.call functions, as stated in the docs for ?call

Note that call() and as.call(), when applicable, are much preferable to these parse() based approaches.

Obviously, we don't have your data to reproduce your example, but here's a minimal example of an S3 class that returns a call captured by match.call put through eval to reproduce the original call:

model <- lm(mpg ~ wt, mtcars)

model$call
#> lm(formula = mpg ~ wt, data = mtcars)

eval(model$call)
#> 
#> Call:
#> lm(formula = mpg ~ wt, data = mtcars)
#> 
#> Coefficients:
#> (Intercept)           wt  
#>      37.285       -5.344

Created on 2022-08-07 by the reprex package (v2.0.1)

Related