如何仅返回函数中存在的对象

时间:2018-02-06 11:13:36

标签: r function return missing-data

我正在尝试编写一个函数,我在其中创建了诸如a,b,c之类的向量。我写了几个条件语句来创建这些向量,其中一些可能不存在于函数的末尾。我正在努力写出函数的返回;我想将它们作为列表返回:

return(list(a, b, c))

但是我需要找到一种方法来重新编写它,例如,如果b不存在,将返回a和c,也许我可以添加“不存在”的消息湾

您能帮我找一个简单的解决方案吗?谢谢!

1 个答案:

答案 0 :(得分:1)

不是最优雅的,但这可以做到。

如果你需要检查是否存在大量对象,那么最好以函数形式写下我在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”也会返回TRUE,因为它会认为“c”指的是(基本R)函数c()