我正在尝试将ar函数转换为Rcpp以尝试加速,因为它涉及for循环.在整个过程中,我需要计算向量条目的平均值,在R中它将像mean(x)一样简单,但它似乎在Rcpp中不起作用,每次都给出0 0作为结果.
我的代码看起来像这样:
cppFunction(
"NumericVector fun(int n, double lambda, ...) {
...
NumericVector y = rpois(n, lambda);
NumericVector w = dpois(y, lambda);
NumericVector x = w*y;
double z = mean(x);
return z;
}")
Run Code Online (Sandbox Code Playgroud)
编辑:所以我认为我的错误是由于上面提到的,并且单个双z的返回只是我试图隔离问题.但是以下代码仍然无效:
cppFunction(
"NumericVector zstat(int n, double lambda, double lambda0, int m) {
NumericVector z(m);
for (int i=1; i<m; ++i){
NumericVector y = rpois(n, lambda0);
NumericVector w = dpois(y, lambda)/dpois(y,lambda0);
double x = mean(w*y);
z[i] = (x-2)/(sqrt(2/n));
}
return z;
}")
Run Code Online (Sandbox Code Playgroud) 我想为一个返回std::pair使用的包中的函数提供一个C++接口Rcpp::interface.但是,编译器会抛出大量错误,从以下开始:
.../Rcpp/include/Rcpp/internal/Exporter.h:31:31: error: no matching
function for call to ‘std::pair<int, int>::pair(SEXPREC*&)’
Exporter( SEXP x ) : t(x){}
Run Code Online (Sandbox Code Playgroud)
这是一个简单的例子:
#include <Rcpp.h>
#include <utility>
// [[Rcpp::interfaces(cpp)]]
// [[Rcpp::export]]
std::pair<int, int> bla()
{
return std::make_pair(1,1);
}
Run Code Online (Sandbox Code Playgroud)
此示例函数的生成代码如下所示:
inline std::pair<int, int> bla() {
typedef SEXP(*Ptr_bla)();
static Ptr_bla p_bla = NULL;
if (p_bla == NULL) {
validateSignature("std::pair<int, int>(*bla)()");
p_bla = (Ptr_bla)R_GetCCallable("testinclude", "testinclude_bla");
}
RObject rcpp_result_gen;
{
RNGScope RCPP_rngScope_gen;
rcpp_result_gen = p_bla();
}
if (rcpp_result_gen.inherits("interrupted-error"))
throw Rcpp::internal::InterruptedException();
if (rcpp_result_gen.inherits("try-error"))
throw Rcpp::exception(as<std::string>(rcpp_result_gen).c_str());
return …Run Code Online (Sandbox Code Playgroud) 我有一个具有两个值的数据集,date如下所示:
date x y
1 2013-05-01 1 2
2 2013-05-02 2 2
3 2013-05-03 3 2
Run Code Online (Sandbox Code Playgroud)
date是as.Date使用包的格式lubridate。
现在,我想拥有mean两个值中的一个,但要在一定的时间范围内使用的值x。
我尝试了以下方法:
mean=(x+y)/2
newdata=ifelse((data$date < 2013-10-01 | date$date > 2014-04-09), mean, x)
Run Code Online (Sandbox Code Playgroud)
但是如果只是将mean所有日期都设为。
在日期中是否可以使用比关系大/小的关系?关于如何进行这项工作的任何建议?
提前致谢
我有 100 个名称为 pattern 的数据框product_<region>。这些名称存储在 vector 中names。
我想检查它们,但我不想输入print(product_<region>, n = 10)100 次。
我试过了
for (name in names) {
print(paste0("product_", name), n = 10)
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为 的输出paste0()是一个字符串——它不是数据框本身。
如何使用其名称作为字符串检索数据框?