通过rcpp中的名称更改矢量元素

时间:2018-06-28 04:32:48

标签: r rcpp

我有一个函数,需要创建一个表(tab,然后更改一个值-函数调用中给定tab.names() == kk的值。

看着http://dirk.eddelbuettel.com/code/rcpp/Rcpp-quickref.pdf,我希望下面的代码能用(用变量名代替"foo"),但是我想这要求元素名是静态的,我的会成功。没错我尝试使用which,但无法编译(从'char'到'Rcpp :: traits :: storage_type <16> :: type {aka SEXPREC *}的无效转换-所以我正在做那里有问题。

#include <RcppArmadillo.h>
#include <algorithm>
//[[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;

// [[Rcpp::export]]
IntegerVector fun(const arma::vec& assignment, int k) {

  // count number of peptides per protein
  IntegerVector tab = table(as<IntegerVector>(wrap(assignment)));
  CharacterVector all_proteins = tab.names(); 

  char kc = '0' + k;

  // what I need a working version of: 
  tab(kc) = 1;  // gets ignored, as does a [] version of the same thing.
  // or
  tab('0' + k) = 1; // also ignored

  int ki = which(all_proteins == kc); // gives me compile errors

  // extra credit
  // tab.names(k-1) = "-1";

  return tab;
}

/*** R
set.seed(23)
  x <- rpois(20, 5)
  k <- 5

  fun(x, k)

  # same thing in R:
  expected_output <- table(x)
  expected_output # before modification
#  x
#   3  4  5  6  7  9 10 12 
#   2  4  3  3  4  2  1  1 

  expected_output[as.character(k)] <- 1 # this is what I need help with
  expected_output

#  x
#   3  4  5  6  7  9 10 12 
#   2  4  1  3  4  2  1  1 

  # extra credit:
  names(expected_output)[as.character(k)] <- -1

*/

我仍在学习rcpp,更重要的是,我仍在学习如何阅读手册页并将正确的搜索字词插入google / stackoverflow。我确信这是基本的知识(并且我乐于接受更好的方法-我目前在问题的初始方法方面像R程序员一样,而不是C ++程序员。)

(顺便说一句-在代码的其他部分中使用了arma::vec,为了简化起见,我没有展示它-我意识到这里没有用。我曾就切换它进行过辩论,但在我已经测试了该部分的原理,它起作用了,我最后要做的就是引入一个额外的错误...)

谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用.findName()方法来获取相关的index

#include <RcppArmadillo.h>
#include <algorithm>
//[[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;

// [[Rcpp::export]]
IntegerVector fun(const arma::vec& assignment, int k) {

  // count number of peptides per protein
  IntegerVector tab = table(as<IntegerVector>(wrap(assignment)));
  CharacterVector all_proteins = tab.names(); 

  int index = tab.findName(std::string(1, '0' + k));

  tab(index) = 1;
  all_proteins(index) = "-1";
  tab.names() = all_proteins;

  return tab;
}

/*** R
set.seed(23)
x <- rpois(20, 5)
k <- 5

fun(x, k)
*/

输出:

> Rcpp::sourceCpp('table-name.cpp')

> set.seed(23)

> x <- rpois(20, 5)

> k <- 5

> fun(x, k)
 3  4 -1  6  7  9 10 12 
 2  4  1  3  4  2  1  1 

答案 1 :(得分:1)

您可以编写自己的函数(使用String代替char):

int first_which_equal(const CharacterVector& x, String y) {

  int n = x.size();
  for (int i = 0; i < n; i++) {
    if (x[i] == y) return(i);
  }

  return -1;
}

此外,似乎tab(kc)会将kc转换为整数表示形式。

相关问题