我试图运行下面的代码,我想读取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格式。
谢谢。
发布于 2021-05-13 13:11:49
我在Python木星笔记本中有使用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')发布于 2021-05-21 22:05:35
在运行代码之前,请确保haven和reader安装在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一样
https://stackoverflow.com/questions/67519641
复制相似问题