[R] which.pmin?

Marc Schwartz MSchwartz at MedAnalytics.com
Fri Jan 21 23:38:01 CET 2005


On Fri, 2005-01-21 at 17:26 -0500, Seung Jun wrote:
> I have two vectors (k.floor and k.ceiling) of integers of the same
> length, and a function (fpr).
> 
>     b <- 10:40
>     k.floor <- floor(log(2) * b)
>     k.ceiling <- ceiling(log(2) * b)
>     fpr.floor <- fpr(b, k.floor)
>     fpr.ceiling <- fpr(b, k.ceiling)
> 
> If R had a element-wise ternary function, I'd like to do something like 
> this:
> 
>     (fpr.floor < fpr.ceiling) ? k.floor : k.ceiling
> 
> That is, I'd like to go through the two vectors in parallel, picking
> the one that returns the lower value of fpr. Failing to find such a
> function, I wrote the following two lines:
> 
>     ind <- sapply(data.frame(rbind(fpr.floor,fpr.ceiling)), which.min)
>     opt.k <- cbind(k.floor,k.ceiling)[1:length(ind)+length(ind)*(ind-1)]
> 
> opt.k is the vector I want, but I guess I abuse some functions here.
> I'd like to ask the experts, What is the proper R-way to do this?
> 
> The API should be like "which.pmin(FUN, X, Y, ...)" that returns a
> vector of the same length as X (and Y), provided that X, Y, ... have
> the same length. Please fill the function body.

I believe that ifelse() is what you seek. Try:

  ifelse(fpr.floor < fpr.ceiling, k.floor, k.ceiling)

See ?ifelse for more information.

HTH,

Marc Schwartz




More information about the R-help mailing list