ACLAN
ACLAN

Reputation: 401

How to return only object that exist in a function

I´m trying to write a function in which I´m creating vectors such as a, b, c. I wrote several conditional statements to create these vectors and some of them might not exist at the end of the function. I´m struggling to write the return of the function; I would like to return them as lists:

return(list(a, b, c))

but I need to find a way to re-write it in a way that for example, if b doesn't exist, a and c will be returned and perhaps I can add a message of "doesn't exist" for b.

Can you please help me in finding an easy solution? Thanks!

Upvotes: 1

Views: 225

Answers (1)

kangaroo_cliff
kangaroo_cliff

Reputation: 6222

Not the most elegant, but this could do it.

If you need to check for the existence of a lot of objects, then it is better to write what I wrote in the if else in a functional form.

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
}

Output

ret <- func()
ret
#$a
#[1] 1
#
#$b
#[1] "b doesn't exist"

Edited the above code to include inherits = FALSE in the exists function. If not exists("c") would return TRUE even when there isn't an object "c" as it would think "c" refer to the (base R) function c().

Upvotes: 1

Related Questions