1

I've defined a python function and I want to integrate it in R, is it possible?

This is the python code I want to integrate:

def set_priority_py(overlap,Priority,IEC_category):
    import pandas as pd
    import numpy as np
    import math as m

    #priority = (3,2,1,4,5,6,7)
    #category = ("a","b","c","d","e","f","g")
    #overlap = (float('NaN'),1,1,1,0,1,1)
    priority = Priority
    category = IEC_category
    #overlap = overlap

    data = pd.DataFrame({'priority':priority,'category':category,'overlap':overlap})

    data['new'] = np.nan
    data['new2'] = np.nan
    #rest = []
    data['rest'] = ""
    for i in range(1, len(data)):
        if data.overlap.loc[i] == True:
            if data.priority.loc[i]<= (data.priority.loc[i-1] if m.isnan(data.new.loc[i-1]) else data.new.loc[i-1]):
                data.new.loc[i] = data.priority.loc[i]
                data.new2.loc[i] = data.category.loc[i]
                #rest.append(data.category[i-1])
                #data.rest[i] = rest
                data.rest.loc[i] = ''.join([str(data.rest.loc[i-1]),',',str(data.category.loc[i-1])])
            else:
                data.new.loc[i] = data.priority.loc[i-1]
                data.new2.loc[i] = data.category.loc[i-1]
                #rest.append(data.category[i])
                #data.rest[i] = rest
                data.rest.loc[i] = ''.join([str(data.rest.loc[i-1]),',',str(data.category.loc[i])])
    data.rest = data.rest.str[1:]
    return data

The result with a random dataframe is:

priority    category    overlap new new2    rest
0   3   a   NaN NaN NaN 
1   2   b   1.0 2.0 b   a
2   1   c   1.0 1.0 c   a,b
3   4   d   1.0 1.0 c   a,b,d
4   5   e   0.0 NaN NaN 
5   6   f   1.0 5.0 e   f
6   7   g   1.0 6.0 f   f,g

Is is possible to create a function that works in R? I've tried to integrate it with "reticulate" package, but my program crashes.

This is the code, when I execute the 2nd line RStudio crashes.

  source_python("set_priority_py.py")
  set_priority(overlap,Priority,IEC_category)

EDIT

The code is working for 20 random samples created in this example:

  overlap <- as.logical(sample(c(0,1),size=20, replace = TRUE))
  Priority<- sample(c(0,1,2,3,4,5,6,7),size=20, replace = TRUE)
  IEC_category<-sample(c("a","b","c","d","e","f","g","h"),size=20, replace = TRUE)
  source_python("set_priority_py.py")
  set_priority(overlap,Priority,IEC_category)
5
  • Perhaps check out reticulate: rstudio.github.io/reticulate Commented Jun 27, 2019 at 8:03
  • 1
    See the reticulate package. Or you can just run python using system or such and get the results back to R Commented Jun 27, 2019 at 8:03
  • I was just about to write the same: infoworld.com/article/3340120/how-to-run-python-in-r.html Commented Jun 27, 2019 at 8:03
  • Where have you defined a function? Functions are created with the def keyword. Commented Jun 27, 2019 at 10:19
  • @gersht, yes I have. Now the post is updated. Commented Jun 27, 2019 at 10:47

1 Answer 1

1

R's reticulate package should be the solution to your problem.

You can create a python script file, calling it for example useful_function.py and have in it

def useful_function(x):
    return x *2

Then in R you can simply load the function to your workspace

library(reticulate)
use_python("/path/to/your/python/interpreter")

# source the created python script
source_python("useful_function.py")

result <- useful_function(2)
print(result)

If you're having additional troubles with reticulate and your code you can post here the error message so we can help you out better.

Sign up to request clarification or add additional context in comments.

6 Comments

Your example is exactly what I've done. I don't have error message, the program crashes.
Does your program crash if you run it in a Python interpreter ? Does it give a error message then?
> source_python("set_priority_py.py") Warning messages: 1: In normalizePath(path.expand(path), winslash, mustWork) : path[1]="C:\PROGRA~3\ANACON~1\envs\rstudio/python.exe": The system cannot find the file specified 2: In normalizePath(path.expand(path), winslash, mustWork) : path[1]="C:\PROGRA~3\ANACON~1\envs\rstudio-1.1.456/python.exe": The system cannot find the file specified
It seems R's having trouble finding your python interpreter, can you try explicitly telling it where it is? Use use_python("/path/to/your/python/interpreter"). I edited my original answer so you get a sense of what it should be like.
where are you saving the .py script though?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.