首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Python接口中运行R代码?

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

Stack Overflow用户
提问于 2021-05-13 12:58:33
回答 2查看 950关注 0票数 0

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

我们已经在系统上安装了R.

代码语言:javascript
复制
from rpy2 import robjects    

robjects.r('''
        library(haven)
        data <- read_csv("filename.csv")
        write_sas(data, "filename.sas7bdat")
        ''')

在运行上面的代码之后,就不会有由这些代码生成的输出,甚至我也不会得到任何错误。

期望输出:试图读取.csv文件,然后以.sas7bdat格式导出数据。(在标准python 3.9.2编辑器中)

python没有这样的功能/库,因此我正在尝试以.sas7bdat格式导出数据。

请建议对上述代码或python中的任何其他方式进行一些更改,通过这些方式,我可以在python中创建/导出.sas7bdat格式。

谢谢。

EN

回答 2

Stack Overflow用户

发布于 2021-05-13 13:11:49

我在Python木星笔记本中有使用R的经验,刚开始的时候有点复杂,但确实起作用了。在这里,我刚刚贴上了我的个人笔记,希望能帮上忙:

代码语言:javascript
复制
# 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,所以我做了:

代码语言:javascript
复制
# 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')
票数 1
EN

Stack Overflow用户

发布于 2021-05-21 22:05:35

在运行代码之前,请确保havenreader安装在R kernel中。

代码语言:javascript
复制
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")

您可以使用任何R函数参数。和我用col_names一样

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67519641

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档