hide package loading message when I render R markdown - r

I can't get this dplyr package loading message to go away:
package 'dplyr successfully unpacked and MD5 sums checked
And here is my current code:
g <- df$Finished
h <- append(g, rep("dummy",519))
i <- data.frame(counts <- table(h))
row.names(i) <- c("In progress", "Completed", "Invited")
colnames(i) <- c("gh", "Count")
i = subset(i,select = -c(gh))
suppressPackageStartupMessages(install.packages("dplyr", repos = "http://cran.us.r-project.org", quiet = TRUE, message=FALSE))
suppressPackageStartupMessages(library(dplyr, quietly = TRUE, warn.conflicts = FALSE, invisible()))
ii<- i %>%
arrange(desc(Count))
u <- ii %>% mutate(Percentage = (ii[,1]/519)*100)
print(u)
It even says "cannot remove prior installation of package 'dplyr'

It's not a package loading message, it's a package installation message (which is why all the message suppression won't help). You probably shouldn't install the package every time. Try something like
if (!require("dplyr")) {
install.packages("dplyr", repos = "http://cran.us.r-project.org",
quiet = TRUE, message=FALSE))
}
If all else fails you could probably use capture.output() to make sure you had intercepted all output.

Related

Trying to install the Performance Analytics in R

I'm trying to install the package 'Performance Analysis' in the R script below:
tryCatch(
expr = {
#library('PerformanceAnalytics', verbose = FALSE, quietly = TRUE)
library("PerformanceAnalytics",lib.loc=.libPaths(),verbose = FALSE, quietly = TRUE)
},
error = function(e){
print(e)
install.packages('PerformanceAnalytics', repos='https://cran.rstudio.com', verbose = FALSE)
#library('PerformanceAnalytics', verbose = FALSE, quietly = TRUE)
library("PerformanceAnalytics",lib.loc=.libPaths(),verbose = FALSE, quietly = TRUE)
}
)
But I'm having the following error message (Version 1.2.1335 of R Studio). Does anyone know if I've made a mistake somewhere?
Thanks
unable to access index for repository https://cran.rstudio.com/bin/windows/contrib/3.1
Installing package into ‘C:/Users/xxxxx/Documents/R/win-library/3.1’
(as ‘lib’ is unspecified)
Warning in install.packages :
unable to access index for repository https://cran.rstudio.com/bin/windows/contrib/3.1
Warning in install.packages :
package ‘PerformanceAnalytics’ is not available (as a binary package for R version 3.1.3)
Error in library("PerformanceAnalytics", lib.loc = .libPaths(), verbose = FALSE, :
there is no package called ‘PerformanceAnalytics’

Problems installing github

Hi I have a problem with github package.
This is my code:
Installing packages:
install.packages("magrittr")
library(magrittr)
install.packages("ggplot2")
library(ggplot2)
install.packages("cowplot")
library(cowplot)
install.packages("usethis")
library(usethis)
install.packages("devtools")
library(devtools)
Here comes the error , when I try to force the installation:
There are 4 options:
1: All
2: CRAN packages only
3: None
4: tibble (2.1.3 -> 3.0.0) [CRAN]
When I press 1 I get this error message:
Installing 1 packages: tibble
Installing package into ‘C:/Users/josem/OneDrive/Documents/R/win-library/3.6’
(as ‘lib’ is unspecified)
There is a binary version available but the source version is later:
binary source needs_compilation
tibble 2.1.3 3.0.0 TRUE
Error: Failed to install 'JLutils' from GitHub:
(converted from warning) package ‘tibble’ is in use and will not be installed
devtools::install_github("larmarange/JLutils", force= TRUE)
install.packages("tidyverse")
library(tidyverse)
library(plyr)
library(dplyr)
library(JLutils)
library(tidyverse)
install.packages("rio")
library(rio)
Then when I choose option 3 I can download jutils package but I can not create dat2 dataframe. I don't know why. It's really frustrating ( yesterday it worked perfectly)`
dat <- rio::import("https://github.com/jincio/COVID_19_PERU/blob/master/docs/reportes_minsa.xlsx?raw=true")
dat1 <- dat %>%
mutate(pos_new = Positivos-lag(Positivos,default = 0),
des_new = Descartados-lag(Descartados,default = 0)) %>%
group_by(Dia) %>%
summarise(pos_new = sum(pos_new), des_new = sum(des_new)) %>%
mutate(cum_pos = cumsum(pos_new),
tot_pruebas = pos_new+des_new)
Here is the error:
(creating dat2):
Error in .f(.x[[i]], ...) : object 'Dia' not found
dat2 <- dat1 %>%
mutate(neg_new = tot_pruebas-pos_new) %>%
dplyr::select(Dia, pos_new, neg_new) %>%
rename(Positivo = pos_new, Negativo = neg_new) %>%
gather(res, count, -Dia) %>%
uncount(count)
I tried everything :(

Elegant way to load a string list of packages in R

Hi I've written the following code:
################# Loadin Require Libraries #################
required.packages <- c('caret','readxl')
for (pkg in required.packages){
if(!require(pkg, character.only = T)){
install.packages(pkg,
character.only = T,
dependencies = T)
library(pkg, character.only = T)
}else{
library(pkg, character.only = T)
}
}
The code shall be ran on a computer of a peer, so to take care of might missing libraries I thought I iterate threw a string list, to check if the package is installed if yes -> load if no -> install and load then. However when a package is not available R still puts out a warning message:
Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE,
logical.return = TRUE, : es gibt kein Paket namens ‘readxl’
My question: is there a better way to check / install a bunch of libraries in R? Should I care about the warning? If it is not important is there a way to surpress this warning getting printed?
Edit: Final solution Thanks to the correct answer provided by #akrun:
################# Loadin Require Libraries #################
lib <- .libPaths()[1]
required.packages <- c('caret','readxl')
i1 <- !(required.packages %in% row.names(installed.packages()))
if(any(i1)) {
install.packages(required.packages[i1], dependencies = TRUE, lib = lib)
}
lapply(required.packages, require, character.only = TRUE)
Update 2021 - Pacman
I found the pacman - package really helpful for exactly this purpose, especially the p_load function. It checks if the package is installed and otherwise tries to install the missing package.
This function is a wrapper for library and require. It checks to see
if a package is installed, if not it attempts to install the package
from CRAN and/or any other repository in the pacman repository list.
So nowadays I start all my scripts that need to be 'portable' with the following lines:
require(pacman)
# Load / Install Required Packages
p_load(dplyr, tidyr, gridExtra, psych)
In this case to load / install dplyr, tidyr, gridExtra & psych
Also nice in this package (if you want to clean up the environment) p_unload
# Unload All packages
p_unload()
Here is one option
Pkgs <- c('caret','readxl')
lib <- .libPaths()[1]
i1 <- !(Pkgs %in% row.names(installed.packages()))
if(any(i1)) {
install.packages(Pkgs[i1], dependencies = TRUE, lib = lib)
}

Highlight R syntax using knitr and Package Highlight

I try to highlight my R code using knit and Highlight pachages with Rstudio, but i have errors when kniting;
There's my code :
opts_chunk$set(fig.width=7, fig.height=5)
opts_knit$set(use.highlight = TRUE)
opts_knit$set(out.format = "html")
opts_chunk$set(highlight = TRUE)
opts_knit$set(...., highlight=FALSE)
render_html()
and when compiling, I have that error
Error in library(package = "parser", character.only = TRUE) :
there is no package called 'parser'
I use R 3.0
Thanks in advance
I think I have fixed this problem in the development version, and you can install it from:
install.packages('knitr', repos = 'http://www.rforge.net/', type = 'source')

Problems installing R packages

I'm setting up a new laptop running Gentoo and wish to install R (as I do on all of my computers!).
However, I've hit a bit of a problem when it comes to installing packages.
I first tried to:
> install.packages(c("ggplot2", "plyr", "reshape2"))
And it duly downloaded all of the packages and its dependencies. However they didn't install reporting.
Error in library(data.table) : there is no package called ‘data.table’
Calls: .First -> library
Execution halted
Error in library(data.table) : there is no package called ‘data.table’
Calls: .First -> library
Execution halted
Error in library(data.table) : there is no package called ‘data.table’
Calls: .First -> library
Execution halted
Error in library(data.table) : there is no package called ‘data.table’
Calls: .First -> library
Execution halted
Error in library(data.table) : there is no package called ‘data.table’
Calls: .First -> library
Execution halted
Error in library(data.table) : there is no package called ‘data.table’
Calls: .First -> library
Execution halted
Error in library(data.table) : there is no package called ‘data.table’
Calls: .First -> library
Execution halted
Error in library(data.table) : there is no package called ‘data.table’
Calls: .First -> library
Not a problem I'll just install the data.table package, unfortunately...
> install.packages("data.table")
trying URL 'http://cran.uk.r-project.org/src/contrib/data.table_1.8.2.tar.gz'
Content type 'application/x-gzip' length 818198 bytes (799 Kb)
opened URL
==================================================
downloaded 799 Kb
Error in library(data.table) : there is no package called ‘data.table’
Calls: .First -> library
Execution halted
The downloaded source packages are in
‘/tmp/RtmpbQtALj/downloaded_packages’
Updating HTML index of packages in '.Library'
Making packages.html ... done
Warning message:
In install.packages("data.table") :
installation of package ‘data.table’ had non-zero exit status
And there is no indication of why installation failed at all, so I've no idea how to go about solving this? A traceback() isn't available either.
GCC is installed and configured as the output of gcc-config shows (and the fact that I can install other software from source no problem).
# gcc-config -l
[1] x86_64-pc-linux-gnu-4.6.3 *
Stumped as to how to go about solving this one. Any thoughts or ideas on how to get more information out of install.packages() welcome.
EDIT : contents of .First as requested....
> .First
function ()
{
library(data.table)
library(foreign)
library(ggplot2)
library(Hmisc)
library(lattice)
library(plyr)
library(rms)
library(xtable)
cat("\nWelcome at", date(), "\n")
}
EDIT 2 : No Rprofile.site but there is /usr/lib64/R/library/base/R/Rprofile which has....
# cat /usr/lib64/R/library/base/R/Rprofile
### This is the system Rprofile file. It is always run on startup.
### Additional commands can be placed in site or user Rprofile files
### (see ?Rprofile).
### Notice that it is a bad idea to use this file as a template for
### personal startup files, since things will be executed twice and in
### the wrong environment (user profiles are run in .GlobalEnv).
.GlobalEnv <- globalenv()
attach(NULL, name = "Autoloads")
.AutoloadEnv <- as.environment(2)
assign(".Autoloaded", NULL, envir = .AutoloadEnv)
T <- TRUE
F <- FALSE
R.version <- structure(R.Version(), class = "simple.list")
version <- R.version # for S compatibility
## for backwards compatibility only
R.version.string <- R.version$version.string
## NOTA BENE: options() for non-base package functionality are in places like
## --------- ../utils/R/zzz.R
options(keep.source = interactive())
options(warn = 0)
# options(repos = c(CRAN="#CRAN#"))
# options(BIOC = "http://www.bioconductor.org")
options(timeout = 60)
options(encoding = "native.enc")
options(show.error.messages = TRUE)
## keep in sync with PrintDefaults() in ../../main/print.c :
options(scipen = 0)
options(max.print = 99999)# max. #{entries} in internal printMatrix()
options(add.smooth = TRUE)# currently only used in 'plot.lm'
options(stringsAsFactors = TRUE)
if(!interactive() && is.null(getOption("showErrorCalls")))
options(showErrorCalls = TRUE)
local({dp <- Sys.getenv("R_DEFAULT_PACKAGES")
if(identical(dp, "")) # marginally faster to do methods last
dp <- c("datasets", "utils", "grDevices", "graphics",
"stats", "methods")
else if(identical(dp, "NULL")) dp <- character(0)
else dp <- strsplit(dp, ",")[[1]]
dp <- sub("[[:blank:]]*([[:alnum:]]+)", "\\1", dp) # strip whitespace
options(defaultPackages = dp)
})
## Expand R_LIBS_* environment variables.
Sys.setenv(R_LIBS_SITE =
.expand_R_libs_env_var(Sys.getenv("R_LIBS_SITE")))
Sys.setenv(R_LIBS_USER =
.expand_R_libs_env_var(Sys.getenv("R_LIBS_USER")))
.First.sys <- function()
{
for(pkg in getOption("defaultPackages")) {
res <- require(pkg, quietly = TRUE, warn.conflicts = FALSE,
character.only = TRUE)
if(!res)
warning(gettextf('package %s in options("defaultPackages") was not found', sQuote(pkg)),
call.=FALSE, domain = NA)
}
}
.OptRequireMethods <- function()
{
if("methods" %in% getOption("defaultPackages")) {
res <- require("methods", quietly = TRUE, warn.conflicts = FALSE,
character.only = TRUE)
if(!res)
warning('package "methods" in options("defaultPackages") was not found', call.=FALSE)
}
}
if(nzchar(Sys.getenv("R_BATCH"))) {
.Last.sys <- function()
{
cat("> proc.time()\n")
print(proc.time())
}
## avoid passing on to spawned R processes
## A system has been reported without Sys.unsetenv, so try this
try(Sys.setenv(R_BATCH=""))
}
###-*- R -*- Unix Specific ----
.Library <- file.path(R.home(), "library")
.Library.site <- Sys.getenv("R_LIBS_SITE")
.Library.site <- if(!nchar(.Library.site)) file.path(R.home(), "site-library") else unlist(strsplit(.Library.site, ":"))
.Library.site <- .Library.site[file.exists(.Library.site)]
invisible(.libPaths(c(unlist(strsplit(Sys.getenv("R_LIBS"), ":")),
unlist(strsplit(Sys.getenv("R_LIBS_USER"), ":")
))))
local({
## we distinguish between R_PAPERSIZE as set by the user and by configure
papersize <- Sys.getenv("R_PAPERSIZE_USER")
if(!nchar(papersize)) {
lcpaper <- Sys.getlocale("LC_PAPER") # might be null: OK as nchar is 0
papersize <- if(nchar(lcpaper))
if(length(grep("(_US|_CA)", lcpaper))) "letter" else "a4"
else Sys.getenv("R_PAPERSIZE")
}
options(papersize = papersize,
printcmd = Sys.getenv("R_PRINTCMD"),
dvipscmd = Sys.getenv("DVIPS", "dvips"),
texi2dvi = Sys.getenv("R_TEXI2DVICMD"),
browser = Sys.getenv("R_BROWSER"),
pager = file.path(R.home(), "bin", "pager"),
pdfviewer = Sys.getenv("R_PDFVIEWER"),
useFancyQuotes = TRUE)
})
## non standard settings for the R.app GUI of the Mac OS X port
if(.Platform$GUI == "AQUA") {
## this is set to let RAqua use both X11 device and X11/TclTk
if (Sys.getenv("DISPLAY") == "")
Sys.setenv("DISPLAY" = ":0")
## this is to allow gfortran compiler to work
Sys.setenv("PATH" = paste(Sys.getenv("PATH"),":/usr/local/bin",sep = ""))
}## end "Aqua"
local({
tests_startup <- Sys.getenv("R_TESTS")
if(nzchar(tests_startup)) source(tests_startup)
})
Looks like data.table is not installed for the user that is running the install.packages command. I think wrapping that .First function in if (interactive()) { } would be a good idea in general. Otherwise, you need to install data.table and any other packages that load at startup since install.packages runs the .Rprofile file when starting
WARNING: You're using a non-UTF8 locale, therefore only ASCII characters will work.
Please read R for Mac OS X FAQ (see Help) section 9 and adjust your system preferences accordingly.
[History restored from /Users/carlosaburto/.Rapp.history]
defaults write org.R-project.R force.LANG en_US.UTF-8
Error: unexpected symbol in "defaults write"
starting httpd help server ... done

Resources