使用RInside读取R控制台

Read R console with RInside

本文关键字:控制台 读取 RInside 使用      更新时间:2023-10-16

我正在使用Rcpp和RInside将一些命令运行到R中。我制作了一个发送命令的个人GUI(在Qt中),我想以std::string格式恢复结果。

示例:

$1+1

结果是:

[1] 2

我想要这个字符串:

"[1] 2〃;

我已经用";作为";以及";as_string";,但由于R.中的内部返回类型,强制转换无效

是否可以读取R控制台输出或其他内容?

编辑:

void RppMainWindow::runLineOnScriptCursor() {
    std::string line = script->getCodeEditor()->lineOnCursor();
    if ( line.empty() || line == INVALID ) {
        return;
    }
    RCommand cmd (script->getConsoleViewer(), r);
    cmd.execute(line);
}
void RCommand::execute(std::string commande) {
    std::string res = executeOnR(commande);
    viewer->addEntry(commande, res);
}
void ConsoleViewer::addEntry(std::string command, std::string result) {
    this->moveCursor(QTextCursor::End);
    QTextCharFormat format;
    format.setFontWeight(QFont::DemiBold);
    format.setForeground(QBrush(QColor("red")));
    this->mergeCurrentCharFormat(format);
    std::string tmp = "> " + command + "n";
    this->insertPlainText(QString(tmp.c_str()));

    this->moveCursor(QTextCursor::End);
    format.setFontWeight(QFont::Normal);
    format.setForeground(QBrush(QColor("blue")));
    this->mergeCurrentCharFormat(format);
    if ( ! result.empty() ) {
        result += "n";
    }
    this->insertPlainText(QString(result.c_str()));
}

ConsoleViewer允许显示类似的基本R控制台

$R命令

如果需要返回

如果您想要

"[1]2"

您需要在您的端部设置一个格式化例程,该例程接收来自RInside的2并预处理[1](其他行也是如此)。这正是print()在R:中的作用

edd@max:~$ R --slave -e 'print(1+1)'
[1] 2
edd@max:~$ R --slave -e 'cat(1+1, "n")'
2 
edd@max:~$

事实上,在我的结果中,我更喜欢cat(),但print()也可以被模仿。