I have an R script that just prints todays date. It runs just fine in Rstudio but when set as a task within a batch file it produces the following error
Warning message:
package 'dplyr' was built under R version 3.4.4
Loading required package: NLP
Warning message:
package 'tm' was built under R version 3.4.4
Error in today() : could not find function "today"
Execution halted
Here is the script:
library(rvest)
library(dplyr)
library(tm)
yesterday <- today()
yesterday <- gsub("-", "", yesterday, fixed=TRUE)
print(yesterday)
Batch File:
"C:\Program Files\R\R-3.4.2\bin\R.exe" CMD BATCH --vanilla --slave "C:\Users\mike\Desktop\Make_Task\TEST_YESTERDAY.R"
timeout /t 5
When you don't know where an R function comes from, I'd recommend searching rdocumentation.org for the name of the function. In these results, you can see that today is from the lubridate package.
Personally, I would recommend removing the external dependency by using the built-in Sys.Date() instead. But adding library(lubridate) to the top of your script should also work (assuming lubridate is installed).
The today() function is from the lubridate package. You probably loaded the package manually inside RStudio, so it's not in your code. Just add library(lubridate) to the beginning of your script and it should be fine.
Alternatively, you could also use Sys.Date() from r-base
Try with lubridate first and then try today() or now() you will get the answer.
install.packages("lubridate")
library("lubridate")
today()
[1] "2021-04-26"
now()
[1] "2021-04-26 07:09:37 UTC"
Related
I try to use the function "get_data_structure" but got an error as below.
Could anyone know how to fix it?
Thank you in advance
get_data_structure("DUR_D")
Error in data.frame(data_structure#concepts) :
trying to get slot "concepts" from an object (class "data.frame") that is not an S4 object
The problem appears to be a bug in the version of the OECD package on CRAN. If you install the development version, it works. First, close R and reopen a clean new session, then run this:
remotes::install_github("https://github.com/expersso/OECD")
library(OECD)
get_datasets()
get_data_structure("DUR_D")
remotes::install_github("https://github.com/expersso/OECD")
library(OECD)
dataset <- "DUR_D"
dstruc <- get_data_structure(dataset)
Try with get_dataset("DUR_D") i.e. without -s. as get_datasets() with -s will return a dataframe of available datasets.
It is a bug in the package OECD 0.2.5.
It works with the package version 0.2.4 which you can install from CRAN's archived package section (https://cran.r-project.org/src/contrib/Archive/OECD).
If you want to access the archived package version directly in R, use the following code:
devtools::install_version("OECD", version = "0.2.4", repos = "https://stat.ethz.ch/CRAN/")
Note that this requires the package 'devtools' to be installed.
I am running several scripts in RStudio and checking syntax errors. I am using source() in a loop to perform those tasks. In some scripts, install.packages("packagename") occurs. My problem is that when i have the required packages already installed in my computer, a message pops up asking me to update the library. In these cases, I would like to be able to "ignore" install.packages("packagename") call and running code to continue without showing any message.
So, how can i check if package installation is required or not while running code via source()?
Bit of a hack, but given the location file, this will list all the packages inside the script:
require(readr)
require(stringr)
listPackages <- function(file)
{
r <- readr::read_file(file)
r = str_replace_all(r, '\\"', "") # remove all quote marks
packages <- str_extract_all(r, regex("(install.packages|library|require|p_load)\\([:alnum:]*\\)*", multiline = TRUE))[[1]]
return(unique(gsub("\\(", "", str_extract(packages, regex("\\([:alnum:]*", multiline = F)))))
}
Example
test.R:
library("ggplot2")
library(stats)
require("cowplot")
require(MASS)
add <- function(x,y) {x+y}
install.packages("cowplot")
p_load(dplyr)
p_load("dplyr")
listPackages("test.R")
# [1] "ggplot2" "stats" "cowplot" "MASS" "cowplot" "dplyr"
I get the following error:
1Error in library(stringr) :
Package 'stringr' version 1.2.0 cannot be unloaded
when loading the following packages in my knitr document:
library(checkpoint)
checkpoint("2017-01-01")
library(stringr)
library(plyr)
library(tidyr)
library(dplyr)
library(knitr)
library(readr)
library(readxl)
library(ggplot2)
library(scales)
library(ggthemes)
library(lubridate)
library(xtable)
library(zoo)
library(gridExtra)
when I remove stringr then I get the error:
Error in mutate_impl(.data, dots) : could not find function "str_sub"
...any ideas? I am using Mac OSX Mavericks. I copied the files over from a Windows 7 (where it worked) and I'm assuming that has something to do with it.
Thank you in advance!
There is a conflict due to the stringr package being newer (2017-02-18) than your checkpoint date of 2017-01-01.
You could clear the conflict by moving the date you use to something later, i.e.
checkpoint("2017-02-18") # or later
Alternatively, if you find you have mixed dependencies that rely on packages that were not all current on the same date, I would recommend having a look at packrat (link), which is designed for that purpose.
Every day, I use date() function in R to create a new working folder named with today's date. But, it does not work as soon as I load lubridate package. date() works again when I remove the package. What does lubridate do so 'date' function work differently? While loading the lubridate package, the message is:
Attaching package: ‘lubridate’. The following object is masked from
‘package:base’: date.
What should be the value of x in date(x) to get today's date and time?
date() #works well
library(lubridate)
date() #does not work now. Error Msg: Error in as.POSIXlt(x, tz = tz(x)) :
#argument "x" is missing, with no default
detach("package:lubridate", unload=TRUE)
date() #now it works again without "x"
Basically lubridate contains a function named "date" so when you load the lubridate package you are using date() function from that package and not from the base package.
If you want to use a specific function from lubridate package just type lubridate::"the name of the function goes here" without loading lubridate package.
The function date() gets masked out by the function that bears the same name lubridate::date()
A workaround is to use base::date()
Our R scripts are used on multiple users on multiple computers and hence there are deviations in which packages are installed on each computer. To ensure that each script works for all users I would like to define a function pkgLoad which will first test if the package is installed locally before loading the library with suppressed startup messages. Using Check for installed packages before running install.packages() as a guide, I tried
pkgLoad <- function(x)
{
if (!require(x,character.only = TRUE))
{
install.packages(x,dep=TRUE, repos='http://star-www.st-andrews.ac.uk/cran/')
if(!require(x,character.only = TRUE)) stop("Package not found")
}
#now load library and suppress warnings
suppressPackageStartupMessages(library(x))
library(x)
}
When I try to load ggplot2 using pkgLoad("ggplot2") I get the following error message in my terminal
Error in paste("package", package, sep = ":") :
object 'ggplot2' not found
> pkgLoad("ggplot2")
Loading required package: ggplot2
Error in library(x) : there is no package called ‘x’
> pkgLoad("ggplot2")
Error in library(x) : there is no package called ‘x’
Any why x changes from ggplot2 to plain old x?
I wrote this function the other day that I thought would be useful...
install_load <- function (package1, ...) {
# convert arguments to vector
packages <- c(package1, ...)
# start loop to determine if each package is installed
for(package in packages){
# if package is installed locally, load
if(package %in% rownames(installed.packages()))
do.call('library', list(package))
# if package is not installed locally, download, then load
else {
install.packages(package)
do.call("library", list(package))
}
}
}
The CRAN pacman package that I maintain can address this nicely. Using the following header (to ensure pacman is installed first) and then the p_load function will try to load the package and then get them from CRAN if R can't load the package.
if (!require("pacman")) install.packages("pacman"); library(pacman)
p_load(qdap, ggplot2, fakePackage, dplyr, tidyr)
Use library(x,character.only=TRUE). Also you don't need the last line as suppressPackageStartupMessages(library(x,character.only=TRUE)) already loads the package.
EDIT: #LarsKotthoff is right, you already load the package inside of the if brackets. There you already use option character.only=TRUE so everything is good if you just remove last to lines of your function body.
Have a look at this nice function:
klick
The following can be used:
check.and.install.Package<-function(package_name){
if(!package_name%in%installed.packages()){
install.packages(package_name)
}
}
check.and.install.Package("RTextTools")
check.and.install.Package("e1071")
Though #maloneypatr function works fine, but it is quite silent and does not respond on success of packages loaded. I built below function that does make some checks on user entry and also respond on the number of packages being successfully installed.
lubripack <- function(...,silent=FALSE){
#check names and run 'require' function over if the given package is installed
requirePkg<- function(pkg){if(length(setdiff(pkg,rownames(installed.packages())))==0)
require(pkg, quietly = TRUE,character.only = TRUE)
}
packages <- as.vector(unlist(list(...)))
if(!is.character(packages))stop("No numeric allowed! Input must contain package names to install and load")
if (length(setdiff(packages,rownames(installed.packages()))) > 0 )
install.packages(setdiff(packages,rownames(installed.packages())),
repos = c("https://cran.revolutionanalytics.com/", "http://owi.usgs.gov/R/"))
res<- unlist(sapply(packages, requirePkg))
if(silent == FALSE && !is.null(res)) {cat("\nBellow Packages Successfully Installed:\n\n")
print(res)
}
}
Note 1:
If silent = TRUE(all capital silent), it installs and loads packages without reporting. If silent = FALSE, it reports successful installation of packages. Default value is silent = FALSE
How to use
lubripack(“pkg1","pkg2",.,.,.,.,"pkg")
Example 1: When all packages are valid and mode is not silent
lubripack(“shiny","ggvis")
or
lubripack(“shiny","ggvis", silent = FALSE)
Output
Example 2: When all packages are valid and mode is silent
lubripack(“caret","ggvis","tm", silent = TRUE)
Output 2
Example 3: When package cannot be found
lubripack(“shiny","ggvis","invalidpkg", silent=FALSE)
Output 3
How to Install Package:
Run below code to download the package and install it from GitHub. No need to have GitHub Account.
library(devtools)
install_github("espanta/lubripack")