James Adams
James Adams

Reputation: 35

Does R have dot notation like Python?

I am currently working on converting, refactoring, and optimizing a code base from R to Python.

The R code base uses the source() function a lot. From my understanding this is similar to importing a python file.

In python I can do the following:
import myFile
myFile.some_function_or_variable_in_the_file

Seems like you can not do this in R, which means I have to look at the R file in the source() function to know the functions and variables.

Also it seems like bad practice to be calling a function or variable from another file without :: or . since this syntax indicates the file source to the left and the variable or function name to the right.

Maybe this is not as big of an issue when you are in R studio but I am working in Jupyter Lab for both the R and Python work. It would be really nice if I did not have to always look at the files I was referencing.

Upon my google searches I found nothing. Any help or information would be helpful.

Upvotes: 0

Views: 105

Answers (2)

Gwang-Jin Kim
Gwang-Jin Kim

Reputation: 9950

source() is as if you put the code of that sourced file into the same script/code. Everything in the sourced file - is in the same namespace - without distinction. So it is NOT comparable with import in Python. Rather it is in Python exec(open('filename').read()) or:

with open('filename') as f:
    exec(f.read())

In R, so far, you have to generate a package if you want to have a namespace.

Defining the sourced file as an own namespace

I also found https://community.rstudio.com/t/is-it-dangerous-to-create-a-namespace-for-functions-in-a-script-without-a-package/91141

Where the function

source_as_ns <- function(namespace, file){
  ns <- namespace::makeNamespace(namespace)
  source(file, local = ns)
  base::namespaceExport(ns, ls(ns))
}

is given. With

# script.R
foo <- function(x) x + 1

You can call:

source_as_ns("bar", "script.R")

bar::foo(1)
# 2

The answer from @G.Grothendieck works too - but it behaves less like a package, since the operator is $ and not ::.

Upvotes: 1

G. Grothendieck
G. Grothendieck

Reputation: 270010

source can import an R script into an environment and then the objects can be accessed by qualification.

myfile <- environment()
source("myfile.R", myfile)

myfile$fun(x, y, z)  # call fun from myfile passing x, y and z
ls(myfile) # show what was sourced into the myfile environment

Also look at the sys.source function, which provides a variation on source and also check out the box and import packages on CRAN.

Upvotes: 3

Related Questions