我有一个很长的参数向量(大约4 ^ 10个元素)和一个索引向量.我的目标是将索引向量中索引的所有参数值加在一起.
例如,如果我有para = [1,2,3,4,5,5,5]和indices = [3,3,1,6]那么我想找到第三个值的累积和(3 )两次,第一个值(1)和第六个(5),得到12.另外还有根据它们的位置扭曲参数值的选项.
我正在尝试加速R实现,因为我称之为数百万次.
我当前的代码总是返回NA,我无法看到它出错的地方
这是Rcpp函数:
double dot_prod_c(NumericVector indices, NumericVector paras,
NumericVector warp = NA_REAL) {
int len = indices.size();
LogicalVector indices_ok;
for (int i = 0; i < len; i++){
indices_ok.push_back(R_IsNA(indices[i]));
}
if(is_true(any(indices_ok))){
return NA_REAL;
}
double counter = 0;
if(NumericVector::is_na(warp[1])){
for (int i = 0; i < len; i++){
counter += paras[indices[i]];
}
} else {
for (int i = 0; i < len; i++){
counter += paras[indices[i]] * warp[i]; …Run Code Online (Sandbox Code Playgroud) 我正在编写一个函数来查找一组值的中位数.数据表示为唯一值的向量(称为'值')和它们的频率向量('freqs').频率通常非常高,因此将它们粘贴出来会占用大量内存.我有一个缓慢的R实现,它是我的代码中的主要瓶颈,所以我正在编写一个自定义Rcpp函数用于R/Bioconductor包.Bioconductor的网站建议不要使用C++ 11,这对我来说是一个问题.
我的问题在于尝试根据值的顺序将两个向量排序在一起.在R中,我们可以使用order()函数.尽管遵循了关于这个问题的建议:C++排序和跟踪索引,我似乎无法使其工作
以下几行是问题所在:
// sort vector based on order of values
IntegerVector idx_ord = std::sort(idx.begin(), idx.end(),
bool (int i1, int i2) {return values[i1] < values[i2];});
Run Code Online (Sandbox Code Playgroud)
这是完整的功能,为了任何人的利益.任何进一步的提示将不胜感激:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double median_freq(NumericVector values, IntegerVector freqs) {
int len = freqs.size();
if (any(freqs!=0)){
int med = 0;
return med;
}
// filter out the zeros pre-sorting
IntegerVector non_zeros;
for (int i = 0; i < len; i++){
if(freqs[i] != 0){
non_zeros.push_back(i);
}
}
freqs = …Run Code Online (Sandbox Code Playgroud) 我有,我会调用大量的函数(大约每次迭代10 ^ 11倍的优化,一些不同的实验).我已经实现了快速版本,但我很难看到如何提高性能."系统"时间很短,用户时间很长.
这是代码,它接受一个整数并返回一个向量,表示该整数是一个不同的基本计数系统(例如,base = 2给出二进制,base = 10给出标准结果).参数k给出了要返回的向量的长度,因此前面可能有很多零.
正如您将看到的,这些函数需要5或7秒才能运行,但它们都不是系统时间.我想了解原因,以及是否有办法加快速度.我有其他功能同样的问题(99%的时间是在一个循环中花费一个功能,但加速200倍只使运行时间减半),但为了清楚起见我显示了这个.
library(Rcpp)
library(microbenchmark)
# Rcpp version of the function
cppFunction('
NumericVector convert10tobase_c(double number_b10, int k, int base = 4){
if(number_b10 >= pow(base, k)){
stop("k is not large enough to contain the number in this base");
}
NumericVector ret(k);
if(k == 1){
return number_b10;
}
for (int i = 1 ;i < k; i++){
double entry = floor(number_b10 / pow(base, (k - i)));
ret[i-1] = entry;
number_b10 = number_b10 - entry * pow(base, …Run Code Online (Sandbox Code Playgroud)