我正在开发Marketing Mix Modeling,我正在关注这篇文章
https://analyticsartist.wordpress.com/2014/01/31/adstock-rate-deriving-with-analytical-methods/
本文定义了adstock函数如下:
adstock <- function(x, rate=0){
return(as.numeric(filter(x=x, filter=rate, method="recursive")))
}
并进一步使用来自R的nlsm
包中的minpack.lm
来计算速率和系数。
model1 <- nlsLM(Applications~b0 + b1 * adstock(Media1, r1) + b2 * adstock(Media2, r2) +
b3 * adstock(Media3, r3) + b4 * adstock(Media4, r4) + b5 * adstock(Media5, r5) +
b6 * adstock(Media6, r6) + b7 * adstock(Media7, r7),
algorithm = "LM",
start = c(b0= 1, b1= 1, b2= 1, b3 = 1, b4 = 1, b5 =1, b6= 1, b7= 1, r1=0, r2=0, r3=0, r4=0, r5=0, r6=0, r7=0),
lower = c(b0=-Inf, b1=-Inf, b2=-Inf, b3 = -Inf, b4 = -Inf, b5 =-Inf, b6= -Inf, b7= -Inf, r1=0, r2=0, r3=0, r4=0, r5=0, r6=0, r7=0),
upper = c(b0= Inf, b1= Inf, b2= Inf, b3 = Inf, b4 = Inf, b5 =Inf, b6= Inf, b7= Inf, r1=0.5, r2=0.5, r3=0.5, r4=0.5, r5=0.5, r6=0.5, r7=0.5))
但是,模型会因以下错误而失败
Error in filter_(.data, .dots = compat_as_lazy_dots(...)) :
argument ".data" is missing, with no default
似乎错误来自adstock函数,但我不知道如何解决它。
我真的希望有人能帮忙解决这个问题。
非常感谢提前!!
(这是一个常见问题,但由于我找不到副本,我现在会提供一个答案。)
你在这里看到的错误来自dplyr::filter
,而不是你期望使用的:stats::filter
。当你加载dplyr
时,你应该在某些时候看到类似下面的内容:
library(dplyr)
# Attaching package: 'dplyr'
# The following objects are masked from 'package:stats':
# filter, lag
# The following objects are masked from 'package:base':
# intersect, setdiff, setequal, union
在使用非基本函数时,他们要明确这一点(并且在将包发布到CRAN时鼓励/强制)。我一般认为stats::
可以免于此,但使用dplyr
肯定会强制要求它。
因此,在filter
附近的任何地方使用dplyr
时,对代码的修复都是明确的:
adstock <- function(x, rate=0){
return(as.numeric(stats::filter(x=x, filter=rate, method="recursive")))
}
FWIW,R的命名空间管理和粗略的等效性与python的更明确的方法:
R Python
---------------------- ----------------------
import pkgname | explicit namespace use
pkgname::function(...) pkgname.function(...) |
import pkgname as p | no R equivalent?
p.function(...) |
library(pkgname) import * from pkgname | permissive namespace,
function(...) function(...) | enables masking