如何 return 仅存在于函数中的对象
How to return only object that exist in a function
我正在尝试编写一个函数,在其中创建诸如 a、b、c 之类的向量。我写了几个条件语句来创建这些向量,其中一些可能在函数结束时不存在。我正在努力编写函数的 return;我想 return 它们作为列表:
return(list(a, b, c))
但我需要找到一种方法来重写它,例如,如果 b 不存在,a 和 c 将被 returned,也许我可以添加一条消息"doesn't exist" 对于 b。
你能帮我找到一个简单的解决方案吗?谢谢!
不是最优雅的,但这可以做到。
如果需要检查很多对象是否存在,那么最好把我在if else中写的写成函数式的
func <- function() {
a <- 1 # so a exists
ret_list <- list()
if (exists("a", inherits = FALSE)) {
ret_list <- c(ret_list, a = a)
} else {
ret_list <- c(ret_list, a = "a doesn't exist")
}
if (exists("b", inherits = FALSE)) {
ret_list <- c(ret_list, b = b)
} else {
ret_list <- c(ret_list, b = "b doesn't exist")
}
ret_list
}
输出
ret <- func()
ret
#$a
#[1] 1
#
#$b
#[1] "b doesn't exist"
编辑编辑以上代码,将 inherits = FALSE
包含在 exists
函数中。如果不是 exists("c")
,即使没有对象 "c" 也会 return TRUE,因为它认为 "c" 指的是(基础 R)函数 c()
。
我正在尝试编写一个函数,在其中创建诸如 a、b、c 之类的向量。我写了几个条件语句来创建这些向量,其中一些可能在函数结束时不存在。我正在努力编写函数的 return;我想 return 它们作为列表:
return(list(a, b, c))
但我需要找到一种方法来重写它,例如,如果 b 不存在,a 和 c 将被 returned,也许我可以添加一条消息"doesn't exist" 对于 b。
你能帮我找到一个简单的解决方案吗?谢谢!
不是最优雅的,但这可以做到。
如果需要检查很多对象是否存在,那么最好把我在if else中写的写成函数式的
func <- function() {
a <- 1 # so a exists
ret_list <- list()
if (exists("a", inherits = FALSE)) {
ret_list <- c(ret_list, a = a)
} else {
ret_list <- c(ret_list, a = "a doesn't exist")
}
if (exists("b", inherits = FALSE)) {
ret_list <- c(ret_list, b = b)
} else {
ret_list <- c(ret_list, b = "b doesn't exist")
}
ret_list
}
输出
ret <- func()
ret
#$a
#[1] 1
#
#$b
#[1] "b doesn't exist"
编辑编辑以上代码,将 inherits = FALSE
包含在 exists
函数中。如果不是 exists("c")
,即使没有对象 "c" 也会 return TRUE,因为它认为 "c" 指的是(基础 R)函数 c()
。