Oliver
Oliver

Reputation: 441

Pass arguments based on pattern matchin to function in R

I do have an arbitrary number of R objects I would like to pass as arguments to a function. The naming convention for the objects is "input_\d+", i.e., the string"input_" followed by one or more digits. A static example for only three of these arguments would look like the following:

my_function <- function(input_1, input_2, input_3)

What would I have to do to make R "look" for all objects satisfying the patter "input_\d+" and pass it to the function (the code of the function can of course handle an arbitrary number of parameters passed).

Any advice would be highly appreciated,

Oli

Upvotes: 2

Views: 78

Answers (2)

pogibas
pogibas

Reputation: 28369

You can use get to search by name for an object.

input_1 <- 1
input_2 <- 2
input_3 <- 3

my_function <- function(input_1) {
    print(input_1^input_1)
}

for(i in 1:3) {
    foo_1 <- get(paste0("input_", i))
    my_function(foo_1)
}

1
4
27

Upvotes: 1

talat
talat

Reputation: 70326

You could use mget and ls to create a named list of all inputs and pass that list to your function which you might need to modify a bit for that kind of input:

my_function(mget(ls(pattern = "^input_\\d+$")))

Upvotes: 5

Related Questions