我有一个函数来计算二次方程的逆.默认情况下,它提供了两种可能的解决方
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
}
Run Code Online (Sandbox Code Playgroud)
如果给出单个y值,这可以正常工作,但如果我从数据框中给它一个列表或一列,那么min和max元素给出了整个列表的最小值.我希望它只返回该元素的最小结果.我假设迭代列表是可能的,但效率不高.
有任何想法吗 ?
更换min(max通过)函数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
Run Code Online (Sandbox Code Playgroud)