我已经定义了一个python函数,我想将其集成到R中,有可能吗?
这是我要集成的python代码:
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
具有随机数据帧的结果是:
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
是否可以创建在R中可用的函数?我尝试将其与“网状”软件包集成,但是我的程序崩溃了。
这是我执行第二行RStudio崩溃时的代码。
source_python("set_priority_py.py")
set_priority(overlap,Priority,IEC_category)
编辑
该代码适用于在此示例中创建的20个随机样本:
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)
答案 0 :(得分:0)
R的reticulate
软件包应该可以解决您的问题。
您可以创建一个python脚本文件,例如将其命名为useful_function.py
def useful_function(x):
return x *2
然后在R中,您只需将函数加载到您的工作空间中
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)
如果您在使用网状结构和代码时遇到其他麻烦,可以在此处发布错误消息,以便我们更好地帮助您。