Inverse of which
My own solution (for now): EDIT as per @Marek's suggestion.
invwhich<-function(indices, outlength, useNames = TRUE)
{
rv<-logical(outlength)
#rv<-rep(FALSE, outlength) #see Marek's comment
if(length(indices) > 0)
{
rv[indices]<-TRUE
if(useNames) names(rv)[indices]<-names(indices)
}
return(rv)
}
It performs very well (apparently better than @Andrie's oneliner) and, in as much as possible, accounts for useNames. But is it possible to make this into a oneliner?
wrt performance, I simply use:
someindices<-sample(1000000, 500000, replace=FALSE)
system.time(replicate(100, tmp<-invwhich(someindices, 1000000)))
as a very lo-fi performance measurement.
One-liner solution:
invwhich <- function(indices, totlength) is.element(seq_len(totlength), indices)
invwhich(c(2,5), 10)
[1] FALSE TRUE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE