首页 > 解决方案 > R如何区分dplyr包中的两个过滤器函数和时间序列中的线性过滤器?

问题描述

我想根据某些条件过滤数据集。当我查看过滤器功能的帮助时,结果是:

filter {stats}  R Documentation
Linear Filtering on a Time Series
Description
Applies linear filtering to a univariate time series or to each series separately of a multivariate time series.

在网上搜索后,我找到了我需要的过滤器功能,即来自 dplyr 包。R怎么能有两个同名的函数。我在这里想念什么?

标签: rfilterdplyrtime-series

解决方案


目前,R 解释器将调用对环境的调用filterdplyr至少如果对象的类在可用方法中:

方法(过滤器) [1] filter.data.frame* filter.default* filter.sf* filter.tbl_cube* filter.tbl_df* filter.tbl_lazy*
[7] filter.ts*

如您所见,有一个ts方法,因此如果对象属于该类,则解释器会将 x 值传递给它。但是,似乎作者dplyr已经阻止了该机制,而是设置了警告功能。您将需要使用:

getFromNamespace('filter', 'stats')
function (x, filter, method = c("convolution", "recursive"), 
    sides = 2L, circular = FALSE, init = NULL) 
{  <omitting rest of function body> }

# same result also obtained with:
stats::filter

R 函数包含在命名空间中,因此函数的完整名称应为:namespace_name::function_name. 命名空间容器的层次结构(实际上是 R 术语中的“环境”)沿着搜索路径排列(这将根据包及其依赖项的加载顺序而有所不同)。-infix ::-operator 可用于指定名称空间或包名称,该名称空间或包名称位于搜索路径的上方,而不是在调用函数的上下文中可能找到的位置。该函数search可以显示当前加载的包的名称及其关联的命名空间。见?search这里是我目前的(这是一个相当臃肿的,因为我回答了很多问题并且通常不会从一个干净的系统开始:

> search()
 [1] ".GlobalEnv"                "package:kernlab"           "package:mice"              "package:plotrix"          
 [5] "package:survey"            "package:Matrix"            "package:grid"              "package:DHARMa"           
 [9] "package:eha"               "train"                     "package:SPARQL"            "package:RCurl"            
[13] "package:XML"               "package:rnaturalearthdata" "package:rnaturalearth"     "package:sf"               
[17] "package:plotly"            "package:rms"               "package:SparseM"           "package:Hmisc"            
[21] "package:Formula"           "package:survival"          "package:lattice"           "package:remotes"          
[25] "package:forcats"           "package:stringr"           "package:dplyr"             "package:purrr"            
[29] "package:readr"             "package:tidyr"             "package:tibble"            "package:ggplot2"          
[33] "package:tidyverse"         "tools:rstudio"             "package:stats"             "package:graphics"         
[37] "package:grDevices"         "package:utils"             "package:datasets"          "package:methods"          
[41] "Autoloads"

目前,我可以使用帮助系统找到 3 个版本的过滤器实例:

?filter

# brings this up in the help panel

Help on topic 'filter' was found in the following packages:

Return rows with matching conditions
(in package dplyr in library /home/david/R/x86_64-pc-linux-gnu-library/3.5.1)
Linear Filtering on a Time Series
(in package stats in library /usr/lib/R/library)
Objects exported from other packages
(in package plotly in library /home/david/R/x86_64-pc-linux-gnu-library/3.5.1)

推荐阅读