user3729066
user3729066

Reputation: 25

Extract parameter values of a function passed into parameter of function

I can access the parameter values passed into a function structured as named list with

compile_name <- function(first_name, last_name){
  paste(first_name, last_name)
}

create_project <- function(project_name,...) {
  print(as.list(match.call()))
}

create_project(project_name = compile_name(first_name = "first", last_name = "last"), more_stuff = "more")


[[1]]
create_project

$project_name
compile_name(first_name = "first", last_name = "last")

$more_stuff 
[1] more

Is there a way to resolve the parameters of the function passed in the parameter (here project_name) as well into a list. In the example above I end up with the function call in the form of a string in the list point for the project_name parameter. Like so:

 [[1]]
create_project

$project_name
  $first_name 
    [1] "first"
  $last_name
    [1] "last"

$more_stuff 
[1] "more"

Also, is there a way to check if a parameter contains a function to react to this inside of the function?

Upvotes: 1

Views: 512

Answers (3)

Derek Burk
Derek Burk

Reputation: 116

compile_name <- function(first_name, last_name){
  paste(first_name, last_name)
}

convert_call_to_list <- function(x) {
  if (is.call(x)) as.list(x) else x
}

create_project <- function(project_name,...) {
  first_pass <- as.list(match.call())
  second_pass <- lapply(first_pass, convert_call_to_list)
  setNames(second_pass, names(first_pass))
}

create_project(project_name = compile_name(first_name = "first", last_name = "last"), more_stuff = "more")
#> [[1]]
#> create_project
#> 
#> $project_name
#> $project_name[[1]]
#> compile_name
#> 
#> $project_name$first_name
#> [1] "first"
#> 
#> $project_name$last_name
#> [1] "last"
#> 
#> 
#> $more_stuff
#> [1] "more"

Created on 2019-02-27 by the reprex package (v0.2.1)

Upvotes: 2

jdobres
jdobres

Reputation: 11957

Here's a function that checks to see whether any of its arguments is of type "language" (i.e., an expression), and if so, further checks to see if any of those arguments are functions:

my_function <- function(a, b) {
  args <- as.list(match.call())[-1]

  if (is.language(args$b)) {
    sub_args <- as.list(match.call(call = substitute(b)))
  }

  if (any(sapply(sub_args, is.symbol))) {
    print('found a sub-function!')
    print(sub_args)
  }
}

my_function(a = 10, b = my_function(1, mean))

[1] "found a sub-function!"

[[1]]
my_function

$a
[1] 1

$b
mean

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 546213

Are you simply looking for list(...)?

create_project = function (project_name, ...) {
    lst = list(...)
    # do something with `lst`.
}

Upvotes: 1

Related Questions