129

2
+1  Q:

## How to apply Min or Max to each result of a function separately?

I have a function to calculate the inverse of a quadratic equation. By default it gives the two possible solutions:

``````invquad<-function(a,b,c,y,roots="both")
{
#Calculate the inverse of a quadratic function y=ax^2+bx+c (i.e. find x when given y.)
#Gives NaN with non real solutions.
root1<-sqrt((y-(c-b^2/(4*a)))/a)-(b/(2*a))
root2<--sqrt((y-(c-b^2/(4*a)))/a)-(b/(2*a))
if (roots=="both")
result<-c(root1,root2)
if (roots=="min")
result<-min(root1,root2)
if (roots=="max")
result<-max(root1,root2)
result
}
``````

This works fine if given a single value of y, but if I give it a list or a column from a dataframe, then the min and max elements give me the minimum value of the whole list. I want it to return just the minimum result for that element. I'm assuming iterating over the list is possible, but it is not very efficient.

Any ideas ?

+1  A:

Have a look at plyr-package - it allows to break a list/data frame into smaller pieces and then apply your function to this subset.

+7  A:

Replace the `min` (`max`) function by `pmin` (`pmax`):

``````> invquad(1,2,3,3,"min")
[1] -2