我在想0123.中用最簡潔的語法來改變位置pos
中的給定(不連續)元素的矢量v1
,另一個矢量(如果我正在使用arma::vec
類)?說R中我會與在arma :: vec的給定位置上更改元素與其他向量中的對應元素
v1 = 1:10
pos = c(2,4,10)
v2 = c(3,8,2)
v1[pos] = v2
做這可能沒有做明確的for
循環?
道歉,如果這是一個很小的問題......
我在想0123.中用最簡潔的語法來改變位置pos
中的給定(不連續)元素的矢量v1
,另一個矢量(如果我正在使用arma::vec
類)?說R中我會與在arma :: vec的給定位置上更改元素與其他向量中的對應元素
v1 = 1:10
pos = c(2,4,10)
v2 = c(3,8,2)
v1[pos] = v2
做這可能沒有做明確的for
循環?
道歉,如果這是一個很小的問題......
我會回答,即使它真的是在Rcpp Gallery: RcppArmadillo Subsetting後已經回答了這個問題。
在犰狳的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
要複製您的例子在犰狳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
耐心的聖... –
非常感謝您的詳細解釋!這太妙了!並再次爲這個可能無關緊要的問題表示歉意 - 我本週纔開始學習Rcpp! –
也許看[RcppArmadillo子集(http://gallery.rcpp.org/articles/armadillo-subsetting/)的一個開始。 –
我曾看過,但這是關於子集,而在我的情況下,我不知道分配選定的元素的新值...猜猜這是微不足道的,但我是新來的Rcpp&RcppArmadillo ... –