过滤器函数与缺少数据参数一起失败

问题描述 投票:1回答:1

我正在开发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函数,但我不知道如何解决它。

我真的希望有人能帮忙解决这个问题。

非常感谢提前!!

r function nls
1个回答
1
投票

(这是一个常见问题,但由于我找不到副本,我现在会提供一个答案。)

你在这里看到的错误来自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
© www.soinside.com 2019 - 2024. All rights reserved.