如何使用rpy2进行预测?

2024-09-27 23:22:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个R代码可以预测硬盘何时会满。在

$ duinfo <- read.table('duinfo.dat', colClasses=c("Date","numeric"), col.names=c("day","usd"))
$ attach(duinfo)
$ totalspace <- 500000
$ model <- lm(day ~ usd)
$ as.Date(predict(model, data.frame(usd = totalspace)), origin="1970-01-01")

我用python编写了以下代码来获取磁盘将满的预测日期,如下所示:

^{pr2}$

如何使用rpy2将最后一条语句转换为python代码?在


Tags: 代码readdatemodelnamestablecoldat
1条回答
网友
1楼 · 发布于 2024-09-27 23:22:20

我能够将代码转换为python:

import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
utils = importr('utils')
stats = importr('stats')
base = importr("base")

data = robjects.r(
    'read.table(file = "duinfo.dat", colClasses=c("Date","numeric"))')
# data = robjects.r(
#    'read.table(file = "duinfo.dat", colClasses=c("Date","numeric"), col.names=c("days","used"))')
robjects.r.attach(data)
totalspace = 500000
# Get used data
c = robjects.IntVector((2,0))
used = data.rx(True, c)

# Get Days
c = robjects.IntVector((1,0))
days = data.rx(True, c)
robjects.globalenv["used"] = used
robjects.globalenv["days"] = days
#
model = stats.lm('days ~ used')
dataf = robjects.DataFrame({})
d = {'used': totalspace}
dataf = robjects.DataFrame(d)
# Use the predict function to extrapolate the model
end_date = base.as_Date(robjects.r.predict(model, dataf), origin="1970-01-01")
rStr = base.format(end_date, format = "%d/%m/%Y")
print(rStr[0])

相关问题 更多 >

    热门问题