我有一个类似下面的函数,它生成具有相似名称的各种变量。在这个函数里面,我想把所有的变量都放到一个列表中。我知道这个例子看起来效率不高,因为我可以从头开始使用列表,但在我的函数中我必须这样做。
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))
}
如何获得以&#34; hello&#34;开头的所有变量?在没有它给出错误的列表中:FUN中的错误(X [[i]],...):object&#39; hello1&#39;运行test_function()
时找不到。将变量放入共享环境时甚至会发生这种情况。
我希望最后的mylist
是班级列表,而不是角色。
谢谢!
答案 0 :(得分:2)
您可以创建一个环境,然后在其中创建变量。然后使用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"
您可以使用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"