Error in XLConnect - r

I am trying to import an excel sheet into r. I used the following code:
x <- loadWorkbook("x.xlsx")
b <- readWorksheet(x, sheet="b")
The first line works fine, however, running the second gives the following error:
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘readWorksheet’ for signature ‘"jobjRef", "character"’
I have no missing values in that sheet.
For the purpose of reproducing, download trial.xlsx from https://github.com/ahmedfsalhin/1stpaper.
system info: Yosemite operating system.

It appears the "root cause" is that you should add code to specify both the function and the package it belongs to. Type XLConnect::loadWorkbook to select the one you want in this case. There's no 'confusion,' or random selection of duplicated function names in R. The choice depends on the load order of all loaded packages. Use search() to see the order in which packages are checked for the command you've entered.
E.g., at present I get
search()
[1] ".GlobalEnv" "package:caTools"
[3] "package:XLConnect" "package:XLConnectJars"
[5] "package:stats" "package:graphics"
[7] "package:datasets" "package:vecsets"
[9] "package:cgwtools" "package:grDevices"
[11] "package:utils" "package:methods"
[13] "Autoloads" "package:base"
You'll notice that anything in your environment (.GlobalEnv) is selected first, and that all loaded libraries override the base package, for example.

After lot of struggle found the solution to this. In R studio go to the packages and remove all the packages related to XLConnect and xlsx. Then instal only XLConnect packages by typing
install.packages("XLConnect", dependencies=TRUE)
After this the issue should not exist.

I had the same problem while testing out three different packages for loading .xlsx files into R (XLConnect, xlsx, gdata). The solution was to specify the namespace for loadWorkbook:
d3_wb = XLConnect::loadWorkbook("Megadataset_v3.xlsx")
d3 = readWorksheet(d3_wb, 1)
Then it works, no matter if xlsx is loaded/installed or not. The error is because there is also a function with the same name in xlsx and it is defaulting to using the wrong one, which depends on the order the packages were loaded.

Try this instead
x <- readWorksheetFromFile("x.xlsx") in XLConnenct package.

Related

How R differentiates between the two filter function one in dplyr package and other for linear filtering in time series?

I wanted to filter a data set based on some conditions. When I looked at the help for filter function the result was:
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.
After searching on web I found the filter function I needed i.e. from dplyr package. How can R have two functions with same name. What am I missing here?
At the moment the R interpreter would dispatch a call to filter to the dplyr environment, at least if the class of the object were among the avaialble methods:
methods(filter)
[1] filter.data.frame* filter.default* filter.sf* filter.tbl_cube* filter.tbl_df* filter.tbl_lazy*
[7] filter.ts*
As you can see there is a ts method, so if the object were of that class, the interpreter would instead deliver the x values to it. However, it appears that the authors of dplyr have blocked that mechanism and instead put in a warning function. You would need to use:
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 functions are contained in namespaces, so a full designation of a function would be: namespace_name::function_name. There is a hierarchy of namespace containers (actually "environments" in R terminology) arranged along a search path (which will vary depending on the order in which packages and their dependencies have been loaded). The ::-infix-operator can be used to specify a namespace or package name that is further up the search path than might be found in the context of the calling function. The function search can display the names of currently loaded packages and their associated namespaces. See ?search Here's mine at the moment (which is a rather bloated one because I answer a lot of questions and don't usually start with a clean systems:
> 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"
At the moment I can find instances of 3 versions of filter using the help system:
?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)

Series of errors with basic functions

I`m a BSc student just getting into R. I've done a bunch of things already (mainly for Psych statistics, plotting and other basic stuff). Yet when I try to knit a script I very often get error Messages. At first it was the same two errors repeatedly;
"trying to use CRAN without setting a mirror"
&
"cannot open the connection Calls: ... withCallingHandlders -> withVIsible -> eval -> eval -> read.table -> file".
Both of which I finally managed to track down (taken from here: Can't resolve error in .Rmd file <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval ->
&
Set default CRAN mirror permanent in R)
And now that I'm finally over the technical issues, I keep getting bogged down in fundamental errors. Like RStudio not recognising basic commands like gather() and %>%, even though I have set the work directory, installed all the packages and put them in the workspace library. And when that didn't work, I copy/pasted someone else's, with the exact same codes that work and it still won't let me knit it to .hmtl.
I can't even check my basic work on any level and I feel like there must be some fundamental issue I'm missing. I've spent several hours a day troubleshooting introductory assignments (and even downloaded it on a different computer) and I keep getting these error messages every time I write any form of code.
Edit:
[Data/HW6.txt] is just a generic table from the teacher for homework 6.
dat_w <- read.table(file="data/HW6.txt", header=TRUE, sep=",")
dat_l <- dat_w %>%
gather(adi:kft, key=Test, value=Score) %>%
arrange(Gruppe, Subj)
To which I put the packages and the commands
library(tidyr)
library(dplyr)
But when I go to knit that, the problem I get is still:
Error in dat_w %>% gather(adi:kft, key = Test, value = Score) %>% arrange(Gruppe, :
could not find function "%>%"
Edit 2: search() results are:
[1] ".GlobalEnv" "package:dplyr" "package:tidyr" "tools:rstudio"
[5] "package:stats" "package:graphics" "package:grDevices" "package:utils"
[9] "package:datasets" "package:methods" "Autoloads" "package:base"

Why might one load a library more than once in an R script?

I am trying to understand some code well enough that I can create the necessary files to make it run it for a client. I thought it was odd that it loads a library within a loop:
for (i in 1:length(ids) ){
library(limma)
# About 80 lines of code
}
Is there any likely reason that someone would want to reload the same library multiple times? I thought that libraries didn't do anything besides provide functions.
I searched the limma user guide for the keywords "library" and "load" and didn't find anything obvious.
I would almost think this were an accident if it weren't the very first line in the loop.
It's a mistake. Change the library call to library(limma, verbose=TRUE) and you'll see that only the first call actually does anything (something is returned invisibly, but they're not using it because it's not being assigned).
For example:
> pkgs <- library(base, verbose=TRUE)
Warning message:
In library(base, verbose = TRUE) :
package ‘base’ already present in search()
> pkgs
# [1] "stats" "graphics" "grDevices" "utils" "datasets"
# [6] "setwidth" "colorout" "methods" "base"

Attaching a temporary namespace to the search path

This question is sort of a follow up to this post as I'm still not fully convinced that, with respect to code robustness, it wouldn't be far better to make typing namespace::foo() habit instead of just typing foo() and praying you get the desired result ;-)
Actual question
I'm aware that this goes heavily against "standard R conventions", but let's just say I'm curious ;-) Is it possible to attach a temporary namespace to the search path somehow?
Motivation
At a point where my package mypkg is still in "devel stage" (i.e. not a true R package yet):
I'd like to source my functions into an environment mypkg instead of .GlobalEnv
then attach mypkg to the search path (as a true namespace if possible)
in order to be able to call mypkg::foo()
I'm perfectly aware that calling :: has its downsides (it takes longer than simply typing a function's name and letting R handle the lookup implicitly) and/or might not be considered necessary due to the way a) R scans through the search path and b) packages may import their dependencies (i.e. using "Imports" instead of "Depends", not exporting certain functions etc). But I've seen my code crash at least twice due to the fact that some package has overwritten certain (base) functions, so I went from "blind trust" to "better-to-be-safe-than-sorry" mode ;-)
What I tried
AFAIU, namespaces are in principle nothing more than some special kind of environment
> search()
[1] ".GlobalEnv" "package:stats" "package:graphics"
[4] "package:grDevices" "package:utils" "package:datasets"
[7] "package:methods" "Autoloads" "package:base"
> asNamespace("base")
<environment: namespace:base>
And there's the attach() function that attaches objects to the search path. So here's what I thought:
temp.namespace <- new.env(parent=emptyenv())
attach(temp.namespace)
> asNamespace("temp.namespace")
Error in loadNamespace(name) :
there is no package called 'temp.namespace'
I guess I somehow have to work with attachNamepace() and figure out what this expects before it is called in in library(). Any ideas?
EDIT
With respect to Hadley's comment: I actually wouldn't care whether the attached environment is a full-grown namespace or just an ordinary environment as long as I could extend :: while keeping the "syntactic sugering" feature (i.e. being able to call pkg::foo() instead of "::"(pkg="pkg", name="foo")()).
This is how function "::" looks like:
> get("::")
function (pkg, name)
{
pkg <- as.character(substitute(pkg))
name <- as.character(substitute(name))
getExportedValue(pkg, name)
}
This is what it should also be able to do in case R detects that pkg is in fact not a namespace but just some environment attached to the search path:
"::*" <- function (pkg, name)
{
pkg <- as.character(substitute(pkg))
name <- as.character(substitute(name))
paths <- search()
if (!pkg %in% paths) stop(paste("Invalid namespace environment:", pkg))
pos <- which(paths == pkg)
if (length(pos) > 1) stop(paste("Multiple attached envirs:", pkg))
get(x=name, pos=pos)
}
It works, but there's no syntactic sugaring:
> "::*"(pkg="tempspace", name="foo")
function(x, y) x + y
> "::*"(pkg="tempspace", name="foo")(x=1, y=2)
[1] 3
How would I be able to call pkg::*foo(x=1, y=2) (disregarding the fact that ::* is a really bad name for a function ;-))?
There is something wrong in your motivation: your namespace does NOT have to be attached to the search path in order to use the '::' notation, it is actually the opposite.
The search path allows symbols to be picked by looking at all namespaces attached to the search path.
So, as Hadley told you, you just have to use devtools::load_all(), that's all...

Getting the contents of a library interactively in R

Is there an equivalent of dir function (python) in R?
When I load a library in R like -
library(vrtest)
I want to know all the functions that are in that library.
In Python, dir(vrtest) would be a list of all attributes of vrtest.
I guess in general, I am looking for the best way to get help on R while running it in ESS on linux. I see all these man pages for the packages I have installed, but I am not sure how I can access them.
Thanks
help(package = packagename) will list all non-internal functions in a package.
Yes, use ls().
You can use search() to see what's in the search path:
> search()
[1] ".GlobalEnv" "package:stats" "package:graphics"
[4] "package:grDevices" "package:utils" "package:datasets"
[7] "package:methods" "Autoloads" "package:base"
You can search a particular package with the full name:
> ls("package:graphics")
[1] "abline" "arrows" "assocplot" "axis"
....
I also suggest that you look at this related question on stackoverflow which includes some more creative approaching to browsing the environment. If you're using ESS, then you can use Ess-rdired.
To get the help pages on a particular topic, you can either use help(function.name) or ?function.name. You will also find the help.search() function useful if you don't know the exact function name or package. And lastly, have a look at the sos package.
help(topic) #for documentation on a topic
?topic
summary(mydata) #an overview of data objects try
ls() # lists all objects in the local namespace
str(object) # structure of an object
ls.str() # structure of each object returned by ls()
apropos("mytopic") # string search of the documentation
All from the R reference card

Resources