Reputation: 8169
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 ?
Upvotes: 1
Views: 432
Reputation: 68839
Replace the min
(max
) function by pmin
(pmax
):
> invquad(1,2,3,3,"min")
[1] -2
> invquad(1,2,3,4,"min")
[1] -2.414214
> invquad(1,2,3,c(3,4),"min")
[1] -2.000000 -2.414214
Upvotes: 7
Reputation: 6649
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.
Upvotes: 1