[英]matrix index subsetting with another matrix
將兩個矩陣(一個和兩個)匹配在一起並提取匹配的矩陣2的索引的快速方法是什么? 矩陣二很大(數百到數千行)。
one
[,1] [,2]
9 11
13 2
head(two)
[,1][,2]
[1,] 9 11
[2,] 11 9
[3,] 2 3
[4,] 13 2
[5,] 2 4
[6,] 3 3
輸出應為(注意索引2如何不是輸出值)
1 4
一種方法是:
a = apply(one, 1, paste0, collapse = "-")
b = apply(two, 1, paste0, collapse = "-")
match(a, b)
#[1] 1 4
我們將兩個矩陣的所有列按行粘貼在一起,然后將它們匹配以得到相同的行。
僅供參考,
a
#[1] "9-11" "13-2"
b
#[1] "9-11" "11-9" "2-3" "13-2" "2-4" "3-3"
您可以編寫一個C ++循環來相當快地完成它
library(Rcpp)
cppFunction('NumericVector matrixIndex(NumericMatrix m1, NumericMatrix m2){
int m1Rows = m1.nrow();
int m2Rows = m2.nrow();
NumericVector out;
for (int i = 0; i < m1Rows; i++){
for (int j = 0; j < m2Rows; j++){
if(m1(i, 0) == m2(j, 0) && m1(i, 1) == m2(j, 1)){
//out[j] = (j+1);
out.push_back(j + 1);
}
}
}
return out;
}')
matrixIndex(m1, m2)
[1] 1 4
盡管我懷疑首先預先分配結果向量會更快,例如
cppFunction('NumericVector matrixIndex(NumericMatrix m1, NumericMatrix m2){
int m1Rows = m1.nrow();
int m2Rows = m2.nrow();
NumericVector out(m2Rows);
for (int i = 0; i < m1Rows; i++){
for (int j = 0; j < m2Rows; j++){
if(m1(i, 0) == m2(j, 0) && m1(i, 1) == m2(j, 1)){
out[j] = (j+1);
//out.push_back(j + 1);
}
}
}
return out;
}')
matrixIndex(m1, m2)
[1] 1 0 0 4 0 0
## 0 == nomatch.
您沒有說“快速”是指計算時間還是人的時間。 如果只需要執行一次,那么如果您優化人員時間,總時間可能是最短的,而Ronak的答案將很難被擊敗,這是明確而可靠的。
如果所有數字均小於某個特定數字(例如,在示例數據中為100),則可以執行類似的操作,但可以使用算術將兩列組合在一起然后匹配。 我懷疑(但尚未測試)這會比轉換為字符向量更快。 當然,根據您的情況,當然還有其他算術選項。
a <- one[,1]*100 + one[,2]
b <- two[,1]*100 + two[,2]
match(a, b)
我們可以使用%in%
which(do.call(paste, as.data.frame(two)) %in% do.call(paste, as.data.frame(one)))
#[1] 1 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.