Álvaro
Álvaro

Reputation: 798

R - How to make a function return nothing (not NULL, just avoid the value from being created)

I have a tryCatch() clause inside a lapply() loop that will either output a data.frame if the input value is valid, or NULL if it doesn't. Thus, the list resulting from that contains elements from both classes. Here an example:

a = list(1, 2, "skere", 3)
b = lapply(a, function(x){
  tryCatch({
    out = data.frame("number" = x,
                     "mod2" = x%%2) # This will fail for characters
    return(out)
  },
  error = function(e) {})
})

The result of print(b) would then be:

[[1]]
  number mod2
1     1    1

[[2]]
  number mod2
1     2    0

[[3]]
NULL

[[4]]
  number mod2
1     3    1

In my case, I want to collapse the list of dataframes into a single dataframe, and dplyr::bind_rows() fortunately omits the NULL from being appended. Therefore, it is not a huge problem now, but it could be a problem in some other case.

So the question is: Is there a way to completely omit the NULL from being returned in the first place?

Upvotes: 1

Views: 1465

Answers (2)

akrun
akrun

Reputation: 886938

Here is an option with discard from purrr

library(purrr)
discard(b, is.null)
#[[1]]
#  number mod2
#1      1    1

#[[2]]
#  number mod2
#1      2    0

#[[3]]
#  number mod2
#1      3    1

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388807

As you already know dplyr::bind_rows(b) will omit NULL values so you don't really need to do anything.

Another way is to just remove those NULL values which can be done using Filter.

Filter(length, b)

#[[1]]
#  number mod2
#1      1    1

#[[2]]
#  number mod2
#1      2    0

#[[3]]
#  number mod2
#1      3    1

Or

b[!sapply(b, is.null)]

Upvotes: 2

Related Questions