Running python in R studio

Hi,
I am trying to install the reticulate package into R. After typing install.packages("reticulate") in the R studio console, I get the following error message:

Warning in install.packages :
  unable to access index for repository https://cran.rstudio.com/src/contrib:
  cannot open URL 'https://cran.rstudio.com/src/contrib/PACKAGES'
Warning in install.packages :
  package ‘reticulate’ is not available (for R version 3.5.0)

I am using R studio from within linux mint 18.2. It seems reticulate package is not supported for R versions 3.5.0? Any help to solve this would be most appreciated. Many thanks

For some reason, you did not reach the url. As a result, R tells you that reticulate is not available, but it is because it is not able to reach the cran url.

Are you in an online environment ? Are you behind some firewall or proxy ?

1 Like

thanks for your reply, I don't think I am behind a firewall or proxy.
I'm using anaconda. I tried using the following command:

install.packages('reticulate', dependencies=TRUE, repos='http://cran.rstudio.com/')

and that seems to install reticulate, although I am still having issues calling python. e.g. if I write a python script called add.py with the following code:

def add(x, y):
  return x + y

and then try to call it from an R script:

library(reticulate)
source_python('add.py')
add(5, 10)

I get the following error messages:

> library(reticulate)
> 
> source_python('add.py')
Error in py_run_file_impl(file, local, convert) : 
  Unable to open file 'add.py' (does it exist?)
> add(5, 10)
Error in add(5, 10) : could not find function "add"

any ideas on what might be causing this will be most appreciated! thanks!

Is the path to app.py correct ? As you used relative path, check that the path is correct according your project directory in rstudio

thanks for reply, how would I set the path in rstudio to find the add.py script?

Right now, source_python() is looking inside your R working directory. If you're not sure what that is, you can find out with getwd(). You can change it with setwd(), but making a script dependent on doing so is kind of a kludge.

Where did you save add.py? Was it inside the working directory? If not, you can:

  • Move add.py to your working directory (even better if you are already working within an RStudio Project, where the working directory is project-specific)
  • Use a relative path to add.py that works with your current working directory as the starting point
  • Use an absolute path

The first option is probably the best (maybe in conjunction with the here package), since it avoids introducing fragile, non-portable paths to your script. If you're anticipating a situation where you want to use python scripts that already live elsewhere, how to manage that gracefully is a much bigger question!

1 Like

thank you! your suggestion of moving add.py to working directory worked! :slight_smile:

1 Like