问题描述
我试图在actuar::dztpois
函数中将子集的平均值作为参数传递。
该函数具有以下语法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,FUN = dztpois)
#pass the mean of the subset as an argument in the dztpois function
我得到了子集平均值,但是不确定是否需要将它们添加到数据帧中,或者是否可以在函数中单独调用它们;我更喜欢后者。
Product_means <- tapply(Data$Quantity_WINS,mean)
我不受ave()
方法的约束,但这是我到目前为止所希望的。
解决方法
如@ jay.sf所建议,将ave()
函数修改为ave(Data$Quantity_WINS,Data$Product,FUN=function(x) dztpois(x,lambda=mean(x)))
就足以解决问题。