From hadley at rice.edu  Tue May 10 15:38:11 2011
From: hadley at rice.edu (Hadley Wickham)
Date: Tue, 10 May 2011 08:38:11 -0500
Subject: [Rd] Which higher-order function
Message-ID: <BANLkTi=CydXKyDQUoY0t9F_VAcYKuPS0ow@mail.gmail.com>

Would it be appropriate to add a Which higher-order function?

Which <- function(f, x) {
   ind <- vapply(x, f, logical(1))
   !is.na(ind) & ind
}

Then Filter would be:

Filter <- function(f, x) x[Which(f, x)]

I think the use of vapply is slightly better than the current
as.logical(sapply(x, f)) because it will return a more informative
error message if the predicate doesn't return a logical vector of the
correct length.

Hadley



-- 
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/



[Rd] Which higher-order function
Hadley Wickham