将子集的平均值作为参数传递给 ave() 中的函数
Passing mean of subset as argument to function in 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)))
足以解决问题。
我正在尝试将子集的平均值作为参数传递给 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)))
足以解决问题。