在 rcpp 中按名称更改向量元素

change vector element by name in rcpp

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

查看 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/Whosebug。我确信这是基本的东西(而且我愿意接受更好的方法 - 我目前认为在解决问题的初始方法方面像 R 程序员,而不是 C++ 程序员。)

(顺便说一句 - arma::vec 的使用用于代码的其他部分,为简单起见我没有显示 - 我意识到它在这里没有用。我讨论过切换它,但决定反对它原则上我已经测试了那部分,它可以工作,我最不想做的就是引入一个额外的错误...)

谢谢!

您可以编写自己的函数(使用 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 转换为整数表示形式。

可以使用.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