如何在函数内部将名称中具有模式的所有变量放入列表中

Kes*_*v M 5 r

我有一个如下所示的函数,它生成具有相似名称的各种变量。在这个函数内部,我想将所有变量放入一个列表中。我知道这个例子看起来不太有效,因为我可以从一开始就使用列表,但在我的函数中,我有必要这样做。

test_function <- function(x) {
    myenv <- new.env()
    myenv$hello1 = "hello1string"
    myenv$hello2 = "hello2string"
    myenv$cello2 = "hello2string"
    mylist <- lapply(ls(name = myenv, pattern = "hello"), get)
    print(class(mylist))
}
Run Code Online (Sandbox Code Playgroud)

如何将所有以“hello”开头的变量放入列表中而不给出错误:Error in FUN(X[[i]], ...) : object 'hello1' not found when running test_function()。当将变量放入共享环境时甚至会发生这种情况。

我希望决赛mylist是班级名单,而不是角色。

谢谢!

Sat*_*ish 3

您可以创建一个环境,然后在其中创建变量。然后使用ls()具有环境名称和正确模式的函数,您可以看到环境中与给定模式匹配的变量列表。

test_function <- function(x) {
  myenv <- new.env()
  myenv$hello1 = "hello1"
  myenv$hello2 = "hello2"
  myenv$cello2 = "hello2"
  mylist <- ls(name = myenv, pattern = "hello")
  print(mylist)
}
test_function(1)
# [1] "hello1" "hello2"
Run Code Online (Sandbox Code Playgroud)

您可以使用它mget来提取环境内变量列表的值。

test_function <- function(x, y, z, pattern) {
  myenv <- new.env()
  ls_vars <- list( hello1 = x,
                   hello2 = y,
                   cello2 = z)
  list2env( ls_vars, myenv )   # add list of variables to myenv environment
  newvar <- "hello3"
  assign(newvar, value = "dfsfsf", envir = myenv)  # assign new variable
  mylist <- ls(name = myenv, pattern = pattern)
  return(mget(mylist, envir = myenv))
}
test_function(x = "hello1", y = "hello2", z = "sdfsd", pattern = "hello")
# $hello1
# [1] "hello1"
# 
# $hello2
# [1] "hello2"
# 
# $hello3
# [1] "dfsfsf"

test_function(x = "hello1", y = "hello2", z = "sdfsd", pattern = "cello")
# $cello2
# [1] "sdfsd"
Run Code Online (Sandbox Code Playgroud)