import as in R
Use the namespace package to generate another namespace aliased to the one you are interested in.
library(namespace)
registerNamespace('ggp', loadNamespace('ggplot2'))
data(iris)
ggp::ggplot(iris, ggp::aes(x = Petal.Length, y = Sepal.Length)) + ggp::geom_point()
Note this has the disadvantage of making the package versioning/installation requirements more opaque for scripts.
How to import an .R file and assign an alias to it? Like import myfile.R as mf
Sounds like you want to define an environment and source a file into it. I find sys.source
useful for this.
I have an example file called "my_test_script.R" which contains:
MYCONSTANT <- 3
testfun <- function(val){
print(val)
}
testfun2 <- function(x){
return(x + MYCONSTANT)
}
Now an example session reading that file into an environment so I can 'alias' the information inside of it as 'tstEnv':
> tstEnv <- new.env()
> sys.source(file = "my_test_script.R", envir = tstEnv, toplevel.env = tstEnv)
> tstEnv$testfun("it works")
[1] "it works"
> tstEnv$testfun2(0)
[1] 3
> tstEnv$testfun2(1)
[1] 4
> tstEnv$MYCONSTANT # I can read my constants too
[1] 3
From [package] import [function] in R
You can explicitly tell R which package should be used for a given function using the package::function()
construction. You can even use that to call functions from packages that you haven't loaded with library
.
library(dplyr) # Has a function called filter()
library(plyr) # Also has a filter() function
dplyr::filter(foo)
plyr::filter(bar)
If you want to make sure you're minimizing the possibility for confusion in your code, I highly recommend the conflicted
package, which forces you to explicitly identify the package for all ambiguous function calls: https://www.tidyverse.org/articles/2018/06/conflicted/
R: How to best import infix operators like % % into my package?
I'm not sure if there's a single best practice in this case.
Using @importFrom
to update the NAMESPACE
file is indeed to be a package-wide directive,
but I've never come across a package that had problems with that,
or reasons to avoid it.
You can annotate several functions with the same @importFrom
directive if you like,
denoting which functions use which imports,
and it won't cause any conflicts;
it's entirely up to you though,
a single one would suffice.
Using @import
might be frowned upon,
but I think it really depends on which package you import.
From your question I gather you use ::
explicitly
(which I would personally say is good practice),
and then you don't even need to alter the NAMESPACE
.
For most cases that would be just fine,
though there can be very special cases that usually need to be considered individually.
These special cases, at least in my experience, are usually related with S4 generics.
Take for instance the base::rowSums
function:
it is not a generic function in base
,
but if the Matrix
package is attached,rowSums
is "transformed" into an S4 generic,
but the generic is not in the base package.
Why that's the case is beyond the scope of this answer
(see ?Methods_for_Nongenerics
for more information),
but it means that if your package uses the notation base::rowSums
,
it would not dispatch to methods from Matrix
.
The only way to support both cases
(i.e. when Matrix
is not used by the user and when it is)
would be to use rowSums
without base::
.
Now, regarding infix operators,
if you wanted to use ::
,
you'd need something like base::`%in%`("a", c("a", "b"))
,
which essentially entails using it as a function and losing the infix syntax,
something you probably don't want.
So unless you have very specific reasons to avoid one or the other,
just use whatever notation you prefer.
I'd personally stick to ::
as much as possible,
but would never use it for infix operators.
import all the functions of a package except one when building a package
The NAMESPACE file is somewhat flexible here, as described in Writing R Extensions.
The two main import directives are:
import(PACKAGE)
which imports all objects in the namespace into your package. The second option is to do specific imports using:
importFrom(PACKAGE, foo)
which gives you access to foo()
without needing the fully qualified reference PACKAGE::foo()
.
But these aren't the only two options. You can also use the except
argument to exclude just a handful of imports:
import(PACKAGE, except=c(foo,bar))
which gives you everything from PACKAGE's namespace but foo()
and bar()
. This is useful - as in your case - for avoiding conflicts.
For roxygen, great catch on figuring out that you can do:
#' @rawNamespace import(PACKAGE, except = foo)
to pass a raw NAMESPACE directive through roxygen.
Crontab R script failing due to import function (Rstudio is closed)
function import is from the rio package. Your automated script fails because you did not load that package rio as in library(rio)
. This could not even have worked in RStudio itself neither if you did not load package rio.
Importing txt file in R --- Why does # symbol in variable names cause problems?
#
symbol is used for comments by default, so change that value to something else and as @JonSpring mentioned having #
symbol in column name is not syntactically valid. So to allow that use check.names = FALSE
.
read.table(text = "|VAR1 |VAR2# |
|12 |F |
|56 |B |
|18 |A |", header = TRUE, fill = FALSE, sep = '|',
strip.white = TRUE, comment.char = "@", check.names = FALSE)[, 2:3]
# VAR1 VAR2#
#1 12 F
#2 56 B
#3 18 A
Related Topics
How to Initialize Empty Data Frame (Lot of Columns at the Same Time) in R
Hosting and Setting Up Own Shiny Apps Without Shiny Server
Error in Plot.New():Figure Margins Too Large, Scatter Plot
How to Increase Font Size in a Plot in R
How to Check If Object (Variable) Is Defined in R
How to Create a Marimekko/Mosaic Plot in Ggplot2
Find the Intersection of Overlapping Ranges in Two Tables Using Data.Table Function Foverlaps
Write Many Files in a for Loop
Display Custom Image as Geom_Point
R Ggplot2 Merge with Shapefile and CSV Data to Fill Polygons
Specifying Colclasses in the Read.Csv
How to Change the Formatting of Numbers on an Axis with Ggplot
Automatically Delete Files/Folders
Code to Import Data from a Stack Overflow Query into R
Add "Filename" Column to Table as Multiple Files Are Read and Bound
File Path Issues in R Using Windows ("Hex Digits in Character String" Error)