R 如何分别对函数的每个结果应用最小值或最大值?
我有一个函数来计算二次方程的倒数。默认情况下,它提供两种可能的解决方案:R 如何分别对函数的每个结果应用最小值或最大值?,r,function,R,Function,我有一个函数来计算二次方程的倒数。默认情况下,它提供两种可能的解决方案: 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)))/
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
}
invquad看一看-它允许将列表/数据帧分解为更小的部分,然后将您的函数应用于此子集。看一看-它允许将列表/数据帧分解为更小的部分,然后将您的函数应用于此子集。将min
(max
)函数替换为pmin
(pmax
):
将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