Home > Software engineering >  no applicable method for 'filter' applied to an object of class "c('double'
no applicable method for 'filter' applied to an object of class "c('double'

Time:10-03

Hey I'm willing to try an example from the 4th edition of the time series analysis and its applications manual (ex.10). When I'm running the code from the book on R, I have this error ;

Error in UseMethod("filter") : no applicable method for 'filter' applied to an object of class "c('double', 'numeric')"

Here is the code;

w = rnorm(150,0,1) # 50 extra to avoid startup problems 
x = filter(w, filter=c(1,-.9), method="recursive")[-(1:50)] # remove first 50 
plot.ts(x, main="autoregression")

Do you know what's wrong and how to solve it?

CodePudding user response:

This happens when another non-base R package with a filter function is loaded.

Package dplyr is the main responsible for the question's error. Not because there's something wrong with the package but, quite on the contrary, because the tidyverse of which it is part is so widely adopted that the conflict between stats::filter and dplyr::filter is by far the most frequent case.

The first example was run in a new R session.

w <- rnorm(150,0,1) # 50 extra to avoid startup problems 
x <- filter(w, filter=c(1,-.9), method="recursive")[-(1:50)] # remove first 50 
plot.ts(x, main="autoregression")

Created on 2022-10-02 with reprex v2.0.2

The error

Now load package dplyr and run exactly the same code. R's namespaces loading code predicts conflits between packages and the user is warned that two objects are masked from package stats, one of them is filter, and 4 others from package base.

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

w <- rnorm(150,0,1) # 50 extra to avoid startup problems 
x <- filter(w, filter=c(1,-.9), method="recursive")[-(1:50)] # remove first 50 
#> Error in UseMethod("filter"):  
#>   no applicable method for 'filter' applied to an object of class "c('double', 'numeric')"

Created on 2022-10-02 with reprex v2.0.2

The solution

The solution is to use the qualified name stats::filter.

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

w <- rnorm(150,0,1) # 50 extra to avoid startup problems 
x <- stats::filter(w, filter=c(1,-.9), method="recursive")[-(1:50)] # remove first 50 
plot.ts(x, main="autoregression")

Created on 2022-10-02 with reprex v2.0.2

  • Related