【问题标题】:How do I apply a custom multi-variate function to each row of a data frame in R?如何将自定义多变量函数应用于 R 中数据框的每一行?
【发布时间】:2013-06-28 00:38:07
【问题描述】:

假设我有一个包含名为“foo”和“bar”的列的数据框

mydata <- data.frame(foo=rnorm(100), bar=rnorm(100))

假设我有一个自定义标量函数,它需要标量输入“x”和“y”并产生一个标量输出,例如

myfunction <- function(x, y) { if (x>0) y else x }

如何将 myfunction 应用于 mydata 的每一行,其中 x 为 foo,y 为 bar?

是的,我知道这个具体的例子非常简单,在 R 中可以很容易地完成,但我对模式很感兴趣。想象一下 myfunction 非常复杂,myfunction 的变量名必须映射到mydata 的列名。一般的解决方案是什么?

【问题讨论】:

    标签: r function dataframe


    【解决方案1】:

    Vectorize 是为这种情况设计的mapply 的语法糖。它对于将复杂的代码向量化以输入到期望它的 R 函数中非常有用,例如 outerintegrateuniroot 等。

    myfunction <- Vectorize(myfunction)
    
    myfunction(mydata$foo, mydata$bar)
    

    【讨论】:

      【解决方案2】:

      您可以使用mapply

      mapply(myfunction, mydata$foo, mydata$bar)
      

      【讨论】:

      • +1 - 概括为do.call(mapply, c(FUN = myfunction, unname(mydata)))
      【解决方案3】:
      mydata <- data.frame(x=rnorm(100), y=rnorm(100))
      myfunction <- function(x, y) { if (x>0) y else x }
      
      # with plyr (requires the argument names to match)
      plyr::mdply(mydata, myfunction)
      
      # with base functions
      with(mydata, mapply(myfunction, x, y))
      

      【讨论】:

      • 对于base函数,我相信应该是with(mydata, mapply(myfunction, foo, bar))
      猜你喜欢
      • 2015-12-05
      • 2016-04-13
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      • 2023-03-02
      • 1970-01-01
      • 2023-03-17
      • 2021-08-07
      相关资源
      最近更新 更多