3

When I ?filter,Rstudio let me choose:

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

Linear Filtering on a Time Series
(in package stats in library C:/Program Files/R/R-3.5.3/library)
Return rows with matching conditions
(in package dplyr in library C:/Users/me/Documents/.checkpoint/2019-12-11/lib/x86_64-w64-mingw32/3.5.3)

When I use filter() in my script,how to know is it stats::filter() or dplyr::filter()?

kittygirl
  • 2,255
  • 5
  • 24
  • 52

2 Answers2

2

You could do the following to find the package name that a function is currently loaded from

environmentName(environment(filter))

As for handling it I would stick with using stats::filter() or dplyr::filter() if it's only a few uses or declaring one as a new function altogther

filter_stats <- stats::filter
filter_stats()

The library conflicted is also useful for conflicts especially with conflict_scout() and conflict_prefer(). You could do conflict_prefer("filter", "stats"), for example, to override the default behavior of the most recent package taking priority. There are a few other alternative methods mentioned on the conflicted libraries readme.

There are also the base calls conflicts() or conflicts(detail = TRUE).

BPipher
  • 108
  • 5
2

The generic solution is to inspect topenv(environment(function_name)) (and potentially calling environmentName on the result). But just printing function_name (i.e. using the name without calling it) also works.

That said, this should generally not be used as a mechanism at runtime; instead, ensure that the expected packages are loaded. The easiest ways of doing this are:

  1. Either use explicit namespace qualification, i.e. dplyr::filter instead of filter; this is best practice in most modern languages, but it can be quite burdensome, especially when doing exploratory analysis.
  2. Always use library instead of require when importing a package. Unlike require, library will raise an error if the corresponding package couldn’t be loaded.
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • then,if I want to use `base::function`,should I add `base::` before function name? – kittygirl May 25 '20 at 15:36
  • @kittygirl Good question. *Generally* people don’t do this. Firstly, it would be unpractical since the resulting R code would be extremely unreadable. Secondly, when people override names from ‘base’ (which they rarely do to start with!) they usually tend to do it in such a way that the function can be used as a drop-in replacement to the ‘base’ function, and it’s generally seen as bad style to do otherwise. Ultimately I am not aware of *anybody* who explicitly uses `base::` except in specific cases. – Konrad Rudolph May 25 '20 at 15:42