代码之家  ›  专栏  ›  技术社区  ›  Melissa Key

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

  •  1
  • Melissa Key  · 技术社区  · 6 年前

    tab tab.names() == k ,在哪里 k

    http://dirk.eddelbuettel.com/code/rcpp/Rcpp-quickref.pdf "foo" which

    #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 用于代码的其他部分,我不想简单地显示这些部分—我意识到它在这里没有用处。我曾讨论过如何转换它,但基于我已经测试过的原则,我决定反对它,它是有效的,我最不想做的就是引入一个额外的bug…)

    2 回复  |  直到 6 年前
        1
  •  2
  •   Ralf Stubner    6 年前

    .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 
    
        2
  •  1
  •   F. Privé    6 年前

    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 以整数表示。