【问题标题】:How to run R Code within Python interface?如何在 Python 界面中运行 R 代码?
【发布时间】:2021-05-13 12:58:33
【问题描述】:

我正在尝试在我想要读取 csv 文件的代码下方运行,然后写入“sas7bdat”。我试过下面的代码。

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

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 格式。

谢谢。

【问题讨论】:

  • 您是否尝试过先在 R 中运行该命令?也许在 R studio 中,您可以洞察出问题所在。然后,您可以修复和更新 python 代码。

标签: r python-3.x rpy2


【解决方案1】:

我有在 Python Jupyter Notebooks 中使用 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')

【讨论】:

    【解决方案2】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      • 2018-12-26
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多