简体   繁体   中英

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+", ie, 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

您可以使用mgetls创建所有输入的命名列表,并将该列表传递给函数,您可能需要针对这种输入进行一些修改:

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM