conflicting filter command in R - r

I am using the usual filter R command. However, when I run this on some data.frame, such basic as filter(data,data$entry==some_data), the output is a time serie. This is obviously related to the time series libraries I imported. How can I fix it ?
I imported the following libraries
library(ggplot2)
library(dplyr)
library(zoo)
library(stringi)
library(gridExtra)
library(rCharts)
library(xts)
library(tseries)
library(forecast)
library(curl)
library(vars)
library(astsa)
library(urca)
library(fGarch)

The default filter when you start R is stats::filter, it is used on time series. dplyr should mask it when loaded, so maybe you didn't load dplyr? Or maybe another package you loaded afterwards masked the dplyr version...
You can always specify the version you need by using package::function notation, e.g., dplyr::filter(data, ...). You can also check on conflicts (multiple definitions of objects) with conflicts().
As a side note, you should not be using $ inside dplyr::filter for the data you pass in, it is built to work with unquoted column names:
filter(data,data$entry==some_data) # bad
filter(data, entry == some_data) # good

Related

Error in df % > % mutate(price_scal = scale(price), hd_scal = scale(hd), : could not find function "% > %" [duplicate]

I'm running an example in R, going through the steps and everything is working so far except for this code produces an error:
words <- dtm %>%
as.matrix %>%
colnames %>%
(function(x) x[nchar(x) < 20])
Error: could not find function "%>%"
I don't understand what the benefit of using this special operator
%>% is, and any feedback would be great.
You need to load a package (like magrittr or dplyr) that defines the function first, then it should work.
install.packages("magrittr") # package installations are only needed the first time you use it
install.packages("dplyr") # alternative installation of the %>%
library(magrittr) # needs to be run every time you start R and want to use %>%
library(dplyr) # alternatively, this also loads %>%
The pipe operator %>% was introduced to "decrease development time and to improve readability and maintainability of code."
But everybody has to decide for himself if it really fits his workflow and makes things easier.
For more information on magrittr, click here.
Not using the pipe %>%, this code would return the same as your code:
words <- colnames(as.matrix(dtm))
words <- words[nchar(words) < 20]
words
EDIT:
(I am extending my answer due to a very useful comment that was made by #Molx)
Despite being from magrittr, the pipe operator is more commonly used
with the package dplyr (which requires and loads magrittr), so
whenever you see someone using %>% make sure you shouldn't load dplyr
instead.
On Windows: if you use %>% inside a %dopar% loop, you have to add a reference to load package dplyr (or magrittr, which dplyr loads).
Example:
plots <- foreach(myInput=iterators::iter(plotCount), .packages=c("RODBC", "dplyr")) %dopar%
{
return(getPlot(myInput))
}
If you omit the .packages command, and use %do% instead to make it all run in a single process, then works fine. The reason is that it all runs in one process, so it doesn't need to specifically load new packages.
One needs to install magrittr as follows
install.packages("magrittr")
Then, in one's script, don't forget to add on top
library(magrittr)
For the meaning of the operator %>% you might want to consider this question: What does %>% function mean in R?
Note that the same operator would also work with the library dplyr, as it imports from magrittr.
dplyr used to have a similar operator (%.%), which is now deprecated. Here we can read about the differences between %.% (deprecated operator from the library dplyr) and %>% (operator from magrittr, that is also available in dplyr)
The pipe operator is not available in base R. You need to load one of the following packages to use it: dplyr, tidyverse or magrittr
Anyone else stumbling upon this for calculating powers of matrices please install this library (dplyr alone not correct)
library(expm)

Peculiar error in dplyr filter

I am working through Hadley Wickham's 2015 ggplot book. In it, there is a line of code (the ggplot2 package is already loaded):
presidential <- subset(presidential, start > economics$date[1])
and it works fine. I tried replacing subset with filter as in:
library(dplyr)
presidential <- filter(presidential, start > economics$date[1])
and I get the error:
Error in `>.default`(start, x) :
comparison (6) is possible only for atomic and list types
If the comparison is incorrect, should it also not affect subset?
I think I found the problem. If I explicitly specify dplyr:: as below, then it works:
presidential <- dplyr::filter(presidential, start > economics$date[1])
This means that some other filter function was overriding the one from dplyr.
In the code that I had posted earlier, I had indicated the library(dplyr) line just before the line of code that I thought was causing the problem, but in reality, dplyr had been loaded earlier as part of my startup script.
It looks like the stats package which also has a filter function was loaded after dplyr was loaded (because dplyr was in my startup script) and hence stats::filter masked dplyr::filter.
I really ought to have checked this first before posting, but it does highlight something about the impacts that loading packages in the startup scripts can have. The other tricky point is that in this situation we do not get any messages about the masking that has occurred.

Lubridate Objects Masked After Loading Data.Table

When I load the data.table package after having already loaded the lubridate package, I get the following error message:
Loading required package: data.table
data.table 1.9.4 For help type: ?data.table
*** NB: by=.EACHI is now explicit. See README to restore previous behaviour.
Attaching package: ‘data.table’
The following objects are masked from ‘package:lubridate’:
hour, mday, month, quarter, wday, week, yday, year
Does anyone know a) what's causing this issue and b) how to prevent these objects within lubridate from being masked?
UPDATE:
The issue associated with the above is that I'm using the quarter function from the lubridate package and, after loading the data.table package, I can no longer do so in the same way.
Specifically, when I run quarter(Date, with_year=TRUE) (where Date is a vector of class = Dates), I now get the following error: Error in quarter(Date, with_year = TRUE) : unused argument (with_year = TRUE).
If I simply, quarter(Date), then I can get the desired output without the attached year. For example, if Date is set as simply May 15, 2015 (today), then quarter(Date) will yield 2 (since we're in the 2nd quarter of 2015), but I'd like it to yield 2015.2, hence the importance of the with_year = TRUE option.
Obviously, I can overcome this by using paste to bind together the year and the output of quarter(Date), but I'd prefer to avoid that work-around.
An object name in a package namespace is masked when a new object is defined with the same name. This can be done by the user assigning the name, or by attaching another package that has an object of the same name.
data.table and lubridate have overlapping function names. If you want the lubridate version to be the default, then the easiest solution is to load data.table first, then load lubridate---thus it will be the data.table versions of these functions that is masked by the "newer" lubridate versions.
library(data.table)
library(lubridate)
Otherwise, the solution is to use :: (as in package::function) to fully specify which version of the function you want to use, for example:
lubridate::quarter(Date, with_year = T)
Another option, which involves a little less typing but is perhaps a little less clear as well, would be to alias the lubridate functions you want in the global environment at the start of your script.
quarter = lubridate::quarter
Any use of quarter() later in the script will use the lubridate version of the function.
Yet another option is the conflicted package, which provides a system for preferring a function from one package. It is a bit more intense and intentional, you should definitely read the documentation before using it, but your script might include something like this:
library(conflicted)
conflict_prefer("quarter", "lubridate")
The package conflicted provides various alternatives and is a good practice to use it while loading libraries to be clear on the masking.
https://github.com/r-lib/conflicted

How to use require(googlesheets) properly?

I recently downloaded googlesheets via
devtools::install_github("jennybc/googlesheets")
and experience some difficulties. When running the script as mentioned in
https://github.com/jennybc/googlesheets I get always:
Error: could not find function "%>%"
How can I solve that problem?
Reproducible example:
Download:
devtools::install_github("jennybc/googlesheets")
require(googlesheets)
Data:
gap_key <- "1HT5B8SgkKqHdqHJmn5xiuaC04Ngb7dG9Tv94004vezA"
copy_ss(key = gap_key, to = "Gapminder")
gap <- register_ss("Gapminder")
Error occurs:
oceania_csv <- gap %>% get_via_csv(ws = "Oceania")
Load the dplyr package first, which provides the %>% operator. This is noted here in the README you link to (suppressMessages is optional):
googlesheets is designed for use with the %>% pipe operator and, to a lesser extent, the data-wrangling mentality of dplyr. The examples here use both, but we'll soon develop a vignette that shows usage with plain vanilla R. googlesheets uses dplyr internally but does not require the user to do so.
library("googlesheets")
suppressMessages(library("dplyr"))
You can install dplyr with
install.packages("dplyr")
See here for more about the pipe operator (%>%).

Error: could not find function "%>%"

I'm running an example in R, going through the steps and everything is working so far except for this code produces an error:
words <- dtm %>%
as.matrix %>%
colnames %>%
(function(x) x[nchar(x) < 20])
Error: could not find function "%>%"
I don't understand what the benefit of using this special operator
%>% is, and any feedback would be great.
You need to load a package (like magrittr or dplyr) that defines the function first, then it should work.
install.packages("magrittr") # package installations are only needed the first time you use it
install.packages("dplyr") # alternative installation of the %>%
library(magrittr) # needs to be run every time you start R and want to use %>%
library(dplyr) # alternatively, this also loads %>%
The pipe operator %>% was introduced to "decrease development time and to improve readability and maintainability of code."
But everybody has to decide for himself if it really fits his workflow and makes things easier.
For more information on magrittr, click here.
Not using the pipe %>%, this code would return the same as your code:
words <- colnames(as.matrix(dtm))
words <- words[nchar(words) < 20]
words
EDIT:
(I am extending my answer due to a very useful comment that was made by #Molx)
Despite being from magrittr, the pipe operator is more commonly used
with the package dplyr (which requires and loads magrittr), so
whenever you see someone using %>% make sure you shouldn't load dplyr
instead.
On Windows: if you use %>% inside a %dopar% loop, you have to add a reference to load package dplyr (or magrittr, which dplyr loads).
Example:
plots <- foreach(myInput=iterators::iter(plotCount), .packages=c("RODBC", "dplyr")) %dopar%
{
return(getPlot(myInput))
}
If you omit the .packages command, and use %do% instead to make it all run in a single process, then works fine. The reason is that it all runs in one process, so it doesn't need to specifically load new packages.
One needs to install magrittr as follows
install.packages("magrittr")
Then, in one's script, don't forget to add on top
library(magrittr)
For the meaning of the operator %>% you might want to consider this question: What does %>% function mean in R?
Note that the same operator would also work with the library dplyr, as it imports from magrittr.
dplyr used to have a similar operator (%.%), which is now deprecated. Here we can read about the differences between %.% (deprecated operator from the library dplyr) and %>% (operator from magrittr, that is also available in dplyr)
The pipe operator is not available in base R. You need to load one of the following packages to use it: dplyr, tidyverse or magrittr
Anyone else stumbling upon this for calculating powers of matrices please install this library (dplyr alone not correct)
library(expm)

Resources