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)
systemor such and get the results back to Rdefkeyword.