gpt4 book ai didi

r - 如何在Rcpp中将R对象打印到stderr?

转载 作者:行者123 更新时间:2023-12-04 18:34:53 24 4
gpt4 key购买 nike

我实现了一个 Python-style dictionary for R ,但没有找到在给定键在字典中没有值时引发错误的好方法。调用 stop很容易,但我想通过打印 R 对象来告诉用户哪个键还没有找到。现在我有:

Rcpp::Rcout << "Key not found: ";
Rcpp::print(key); # <-- how can I get this on stderr?
Rcpp::stop("Key error!");

这会将消息打印到标准输出,但我宁愿将其放在标准错误上。可能我只是缺少 Rcpp 提供的功能?

这是一个 MWE:
library(Rcpp)

sourceCpp(code='

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
void test(SEXP key) {
Rcpp::print(key);
Rcpp::Rcerr << "This does not work: " << key << std::endl;
}

/*** R
test("x")
test(c(1,2,3))
*/

')

最佳答案

这工作得很好:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
std::string test(std::string key) {
Rcpp::Rcerr << "Key not found: "<< key << std::endl;
Rcpp::stop("Key error!");
return key;
}

/*** R
test("x")
*/

输出:
Key not found: x
Error in eval(expr, envir, enclos) : Key error!

编辑:

好的,所以您传递了一个可以是单个值或向量的 SEXP。我建议将其转换为字符向量:
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
void test(SEXP key) {
CharacterVector key1 = as<CharacterVector>(key);
Rcpp::Rcerr << "This does not work: " << key1 << std::endl;
}

/*** R
test(c("x", "y"))
test(1:3)
*/

输出:
> Rcpp::sourceCpp('E:/temp/ttt.cpp')

> test(c("x", "y"))
This does not work: "x" "y"

> test(1:3)
This does not work: "1" "2" "3"

关于r - 如何在Rcpp中将R对象打印到stderr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35982284/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com