Home > database >  Does R have dot notation like Python?
Does R have dot notation like Python?

Time:11-16

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.

CodePudding user response:

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.

CodePudding user response:

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 box and import packages on CRAN.

  • Related