简体   繁体   English

将基于模式matchin的参数传递给R中的函数

[英]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. 我确实有任意多个R对象,我想将它们作为参数传递给函数。 The naming convention for the objects is "input_\\d+", ie, the string"input_" followed by one or more digits. 对象的命名约定为“ input_ \\ d +”,即字符串“ input_”,后跟一个或多个数字。 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). 我该怎么做才能使R“满足”所有满足模式“ input_ \\ d +”的对象并将其传递给函数(该函数的代码当然可以处理传递的任意数量的参数)。

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. 您可以使用get按名称搜索对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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