使用其他向量中的相应元素更改 arma::vec 中给定位置的元素

Change elements at given positions in an arma::vec with corresponding elements in other vector

我想知道 Rcpp 中最紧凑的语法是什么,用于将向量 v1 中位置 pos 处的给定(非连续)元素更改为另一个向量中的相应元素(如果我使用 arma::vec class)?说说我会用

在 R 中做什么
v1 = 1:10
pos = c(2,4,10)
v2 = c(3,8,2)
v1[pos] = v2

这是否可以不进行显式 for 循环?

抱歉,如果这是一个微不足道的问题...

我要回答这个问题,即使 Rcpp Gallery: RcppArmadillo Subsetting post 中确实已经回答了这个问题。

子集操作

在犰狳中,API 有 submatrix views 可以使这个操作发生。

#include <RcppArmadillo.h>
using namespace Rcpp;

// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
arma::vec so_subset_params(arma::vec x, arma::uvec pos, arma::vec vals) {
    // Subset and set equal to
    x.elem(pos) = vals;
    return x;
}

/*** R
v1 = 1:10
pos = c(2,4,10)
v2 = c(3,8,2)
so_subset_params(v1, pos-1, v2)    
*/

这将得到:

      [,1]
 [1,]    1
 [2,]    3
 [3,]    3
 [4,]    8
 [5,]    5
 [6,]    6
 [7,]    7
 [8,]    8
 [9,]    9
[10,]    2

在犰狳中复制 R 代码

要在犰狳中 100% 复制您的示例,请使用:

// [[Rcpp::export]]
void so_subset() {

  // --------------- 1:10
  arma::vec v1 = arma::linspace(1,10,10);

  Rcpp::Rcout << "Initial values of V1:" << std::endl << v1 << std::endl;

  // --------------- pos=c(2,4,10)

  // One style to create a subset index
  arma::uvec pos(3);
  pos(0) = 2; pos(1) = 4; pos(2) = 10;

  Rcpp::Rcout << "R indices pos:" << std::endl << pos << std::endl;


  // Adjust for index shift R: [1] => Cpp: [0]
  pos = pos - 1;

  Rcpp::Rcout << "Cpp indices pos:" << std::endl << pos << std::endl;


  // --------------- v2 = c(3,8,2)

  // C++98
  arma::vec v2;
  v2 << 3 << 8 << 2 << arma::endr;

  // C++11
  // arma::vec v2 = { 3, 8, 2}; // requires C++11 plugin

  Rcpp::Rcout << "Replacement values v2:" << std::endl << v2 << std::endl;

  // --------------- v1[pos] = v2

  // Subset and set equal to
  v1.elem(pos) = v2;

  Rcpp::Rcout << "Updated values of v1:" << std::endl << v1 << std::endl;
}

/*** R
so_subset()
*/

因此,您将获得与每个操作相关的以下输出。

Initial values of V1:
    1.0000
    2.0000
    3.0000
    4.0000
    5.0000
    6.0000
    7.0000
    8.0000
    9.0000
   10.0000

R indices pos:
         2
         4
        10

Cpp indices pos:
        1
        3
        9

Replacement values v2:
   3.0000
   8.0000
   2.0000

Updated values of v1:
   1.0000
   3.0000
   3.0000
   8.0000
   5.0000
   6.0000
   7.0000
   8.0000
   9.0000
   2.0000