Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/visual-studio/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python接口中运行R代码?_R_Python 3.x_Rpy2 - Fatal编程技术网

如何在Python接口中运行R代码?

如何在Python接口中运行R代码?,r,python-3.x,rpy2,R,Python 3.x,Rpy2,我试图运行下面的代码,我想读csv文件,然后写“sas7bdat”。我试过下面的代码 我们已经在系统上安装了R的必备库 from rpy2 import robjects robjects.r(''' library(haven) data <- read_csv("filename.csv") write_sas(data, "filename.sas7bdat") ''')

我试图运行下面的代码,我想读csv文件,然后写“sas7bdat”。我试过下面的代码

我们已经在系统上安装了R的必备库

from rpy2 import robjects    

robjects.r('''
        library(haven)
        data <- read_csv("filename.csv")
        write_sas(data, "filename.sas7bdat")
        ''')
从rpy2导入对象
robjects.r(“”)
图书馆(避风港)

数据我有在Python Jupyter笔记本中使用R的经验,开始时有点复杂,但确实有效。这里我只是粘贴了我的个人笔记,希望这些帮助:

# Major steps in installing "rpy2":
# Step 1: install R on Jupyter Notebook: conda install -c r r-essentials
# Step 2: install the "rpy2" Python package: pip install rpy2 (you may have to check the version)
# Step 3: create the environment variables: R_HOME, R_USER and R_LIBS_USER 
# you can modify these environment variables in the system settings on your windows PC or use codes to set them every time)

# load the rpy2 module after installation
# Then you will be able to enable R cells within the Python Jupyter Notebook
# run this line in your Jupyter Notebook
%load_ext rpy2.ipython
我的工作是用Python编写ggplot2,所以我做到了:

# now use R to access this dataframe and plot it using ggplot2
# tell Jupyter Notebook that you are going to use R in this cell, and for the "test_data" generated using the Python
%%R -i test_data 
library(ggplot2)

plot <- ggplot(test_data) + 
        geom_point(aes(x,y),size = 20)
plot
ggsave('test.png')
#现在使用R访问此数据帧,并使用ggplot2进行打印
#告诉Jupyter Notebook,您将在这个单元格中使用R,并用于使用Python生成的“test_数据”
%%R-i测试数据
图书馆(GG2)

绘图在运行代码之前,请确保
haven
reader
安装在
R内核中

from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage

string = """
         write_sas <- function(file, col_names = TRUE, write_to){
             
             data <- readr::read_csv(file, col_names = col_names)
             haven::write_sas(data, path = write_to)
 print(paste("Data is written to ", write_to))

}
""" 

rwrap = SignatureTranslatedAnonymousPackage(string, "rwrap")

rwrap.write_sas( file = "https://robjhyndman.com/data/ausretail.csv", 
                col_names = False,
                write_to = "~/Downloads/filename.sas7bdat")
从rpy2.robjects.packages导入SignatureTranslatedAnonymous包
string=”“”

您是否尝试过先在R中运行该命令?也许在R studio中,您可以了解出了什么问题。然后,您可以修复并更新python代码。