简体   繁体   English

如何使用rpy2从Python传递日期到R

[英]How to pass a date to R from Python using rpy2

I want to call a function from R which requires a Date object. 我想从R调用一个需要Date对象的函数。 I'm struggling to call this function using Rpy2. 我很难用Rpy2来调用这个函数。

Here's an example: An R function that takes a date 这是一个例子:一个采用日期的R函数

d <- as.Date("2009-08-17")
format(d, "%d/%m/%Y")
[1] "17/08/2009"

Now I want to call this function from python 现在我想从python中调用这个函数

import datetime as dt
import rpy2.robjects.packages as rpackages
base = rpackages.importr("base") 
d = dt.date(year=2009, month=8, day=17)
base.format(date, format = "%d/%m/%y")

The last line throws the exception 最后一行抛出异常

NotImplementedError: Conversion 'py2ri' not defined for objects of type    '<class 'datetime.datetime'>'

Any ideas how I can pass dates from python to function in R expecting as.Date(xxx) arguments? 任何想法如何我可以将日期从python传递给R中的函数期待as.Date(xxx)参数?

fyi - I'm not looking for pure python code to convert the format of the date string. fyi - 我不是在寻找纯python代码来转换日期字符串的格式。 I want to know how to pass dates via rpy2 我想知道如何通过rpy2传递日期

Currently, you are not running the as.Date() function, translated as base.as_Date() . 目前,您没有运行as.Date()函数,转换为base.as_Date() Consider doing so and then formatting to string. 考虑这样做,然后格式化为字符串。 But first format the Python datetime object to string with strfttime : 但首先使用strfttime将Python datetime对象格式化为string:

import datetime as dt
import rpy2.robjects.packages as rpackages
import rpy2.robjects as robjects

base = rpackages.importr("base") 
pyDate = dt.date(year=2009, month=8, day=17)

rDate = base.as_Date(pyDate.strftime("%Y-%m-%d"))
rStr = base.format(rDate, format = "%d/%m/%Y")

print(robjects.StrVector(rStr).r_repr())
# "17/08/2009"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM