r - 将子集的平均值作为参数传递给 ave() 中的函数
问题描述
我试图将子集的平均值作为函数中的参数传递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, 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()
方法的约束,但这是我迄今为止发现的。
解决方案
正如@jay.sf 所建议的,将ave()
函数修改ave(Data$Quantity_WINS, Data$Product, FUN=function(x) dztpois(x, lambda=mean(x)))
为足以解决问题。
推荐阅读
- oracle-apex - 在 Oracle Apex 经典报告中显示星级
- python - werkzeug 的 LocalProxy.__local,它在哪里初始化?
- javascript - JSON 数组项返回未定义
- spring-data-jpa - Spring JPA 在 @Embeddable 类中使用主键
- swift - Firebase swift跨应用用户共享不起作用
- javascript - 如何从容器对象中过滤非空对象?
- c - 如何在我的 C 代码中跟踪核心转储?
- c# - 如何解决这个二阶方程计算?
- django - 如何使用 DRF JWT resfresh
- apache-camel - 无法使用骆驼占位符在 application.properties 中设置 azure blobname