【问题标题】:How to apply Min or Max to each result of a function separately?如何将 Min 或 Max 分别应用于函数的每个结果?
【发布时间】:2010-12-02 13:41:48
【问题描述】:

我有一个函数来计算二次方程的逆。默认情况下,它提供了两种可能的解决方案:

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
}

如果给定一个 y 值,这可以正常工作,但如果我给它一个列表或数据框中的一列,那么 min 和 max 元素会给我整个列表的最小值。我希望它只返回该元素的最小结果。我假设迭代列表是可能的,但效率不高。

有什么想法吗?

【问题讨论】:

    标签: r function


    【解决方案1】:

    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
    

    【讨论】:

      【解决方案2】:

      查看plyr-package - 它允许将列表/数据框分成更小的部分,然后将您的函数应用于此子集。

      【讨论】:

        猜你喜欢
        • 2015-02-27
        • 1970-01-01
        • 1970-01-01
        • 2021-08-13
        • 2022-12-13
        • 2022-07-14
        • 2021-04-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多