user1815498
user1815498

Reputation: 1287

skipping NULL output in apply

When using apply in R, is there some way to have it skip over vector elements that are NULL, such that when f(x2,y2) is undefined apply(x,1,f,y) returns

c(f(x1,y1),f(x1,y2),f(x2,y2))
rather than
c(f(x1,y1),f(x1,y2),NULL,f(x2,y2))?

Upvotes: 2

Views: 560

Answers (2)

Chechy Levas
Chechy Levas

Reputation: 2312

You can do it using foreach and outputting a dataframe:

foreach(i = 1:4, .combine = rbind) %do% {
  if (i == 3) {
    data.frame(i = numeric())
  } else {
    data.frame(i=i)
  }
}

Upvotes: 0

Ricardo Saporta
Ricardo Saporta

Reputation: 55420

afaik, not from inside the apply loop.

Your two options are:

  1. to filter x & y. This can be done before calling apply, or in the actual apply call. eg: apply(x[index.x], 1, f, y[index.y])
  2. to filter the results after you get them. eg

    res <- apply(x,1,f,y)
    res <- res[!is.na(res)]

edit:

If going with the latter option, depending on what the output of your function is, either is.null(res) or is.na(res) will be the correct function to use.

Upvotes: 1

Related Questions