Reputation: 1287
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
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
Reputation: 55420
afaik, not from inside the apply loop.
Your two options are:
apply(x[index.x], 1, f, y[index.y])
to filter the results after you get them. eg
res <- apply(x,1,f,y)
res <- res[!is.na(res)]
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