如何使用 r::apply() 应用我自己的函数

How to apply my own function with r::apply()

我有以下数据框

   GRATE GSHAPE
1  0.04    1.0
2  0.08    0.5
3  0.12    2.0

我想通过以下函数计算新列 COL

myfun = function (Rmax=150, precision=0.1, grate, gshape){
  s = seq(0,Rmax,precision)
  R = pgamma(s, rate=grate, shape=gshape)
  Rc = 1-R
  Rc2 = Rc^2
  Rc2ds = Rc2*precision
  intRc2ds = sum(Rc2ds, na.rm=TRUE)
  return(intRc2ds)
}

这不能正常工作:

mydf$COL = apply(mydf, 2, myfun, grate=mydf$GRATE, gshape=mydf$GSHAPE)

我应该怎么做?

你到底想完成什么?使其 运行 跨列没有意义,因为这样你就永远不会同时拥有 grate 和 gshape,而是一次只有一个。

如果您想 运行 跨行(这样您就可以得到行中显示的 grate 和 gshape 组合的答案),此代码有效:

mydf$COL = apply(mydf, 1, function(x) {myfun(grate=x[1], gshape=x[2])})

这是一个 apply() 的解决方案(灵感来自 @kneijenhuijs )

myfun = function (grate.gshape, Rmax=150, precision=0.1) {
  grate <- grate.gshape[1]; gshape <- grate.gshape[2]
  s = seq(0, Rmax, precision)
  Rc2ds = (1-pgamma(s, rate=grate, shape=gshape))^2 *precision
  sum(Rc2ds, na.rm=TRUE) # intRc2ds
}
apply(mydf, 1, myfun)

您可以根据 apply()

的“...”参数设置其他参数

首先我用 mapply() 得到了这个解决方案:

mydf <- read.table(header=TRUE, text='GRATE GSHAPE
1  0.04    1.0
2  0.08    0.5
3  0.12    2.0')

myfun = function (grate, gshape, Rmax=150, precision=0.1){
  s = seq(0,Rmax,precision)
  R = pgamma(s, rate=grate, shape=gshape)
  Rc = 1-R
  Rc2 = Rc^2
  Rc2ds = Rc2*precision
  intRc2ds = sum(Rc2ds, na.rm=TRUE)
  return(intRc2ds)
}

mapply(myfun, mydf$GRATE, mydf$GSHAPE)

但是其他参数(Rmax=和precision=)就很难设置了。 另一种解决方案可以是 Vectorize(myfun, ...)。生成的函数可以使用向量。