首页 > 解决方案 > 将子集的平均值作为参数传递给 ave() 中的函数

问题描述

我试图将子集的平均值作为函数中的参数传递actuar::dztpois

'actuar' 包 - 第 133 页

该函数具有以下语法dztpois(x, lambda, log = FALSE),其中 lambda 是 x 的平均值。我尽我所能,但现在我需要了解在子集上运行函数并添加参数的最佳实践。从其他帖子中,我看到该ave()函数是合适的,我之前成功使用过,但没有传递参数。

Data <- data.frame(
  Product = sample(c("A", "B", "C"), 100, replace = TRUE),
  Quantity = sample(1:100)
  )

# Winsorize data by group (Product) and add results to new column ---------
library(DescTools)
Data$Quantity_WINS <- ave(Data$Quantity, Data$Product, FUN = Winsorize)
Data$Quantity_WINS <- round(Data$Quantity_WINS)

# Calculate dtzpois value by group (Product) and add to column ------------
library(actuar)
Data$Quantity_DZTPOIS <- ave(Data$Quantity_WINS, Data$Product, FUN = dztpois)
#pass the mean of the subset as an argument in the dztpois function

我得到了子集的意思,但不确定是否需要将它们添加到数据框中,或者是否可以在函数中单独调用它们;我更喜欢后者。

Product_means <- tapply(Data$Quantity_WINS, Data$Product, mean)

我不受这种ave()方法的约束,但这是我迄今为止发现的。

标签: rsubsetmean

解决方案


正如@jay.sf 所建议的,将ave()函数修改ave(Data$Quantity_WINS, Data$Product, FUN=function(x) dztpois(x, lambda=mean(x)))为足以解决问题。


推荐阅读