2017-06-28 17 views
-1

マトリックスBの中に5つまたは4つの番号しかない行列Aを取得したいと思います。 ?必要な最大一致数に基づいて2つの行列間の値を一致させよう

ΜatrixA

1 2 3 4 5 
2 3 5 6 7 
3 5 7 8 1 
2 7 5 4 3 

行列B:

1 2 4 5 6 
2 4 1 3 7 
3 5 7 9 8 
5 8 9 2 6 

IはAの行に一致するようにBから5つの数字を求める場合、私は一致する行を取得しないであろう。

私が得るAIの行と一致するようにBから4つの数字を求める場合:

B1 - A1 
B2 - A1, A4 
B3 - A3 
+0

B3はA1、A2、B4とA2をどのように一致させますか? – Sotos

+0

あなたは正しいです、私はそれを変更しました。 – user8102905

答えて

1

私が動作するRに内蔵されて何も知らないが、このカスタム関数は、あなたが何を得るのを助けることあなたは後です。

find.matches <- function(A, B, num.matches){ 
    # Set rownames for the matrix 
    rownames(A) = paste0(deparse(substitute(A)), 1:nrow(A)) 
    rownames(B) = paste0(deparse(substitute(B)), 1:nrow(B)) 

    # Create matrix indicating matching items 
    out <- t(apply(cbind(seq_len(nrow(B)),B), 1, 
        function(y) { 
        cur.b = y[-1] 
        res <- apply(cbind(seq_len(nrow(A)),A), 1, 
          function(z) { 
          cur.a = z[-1] 
          ifelse(sum(table(cur.a[cur.a %in% cur.b])) == num.matches, rownames(A)[z[1]], NA)})})) 

    # Create list of matching items 
    out <- apply(out, 1, function(x) paste(x[!is.na(x)])) 

    # Remove non matches from list 
    out <- out[lapply(out,length) > 0] 

    if(length(out) > 0){ 
    # Convert list to a vector 
    out <- paste0(names(out), " - ", lapply(c(out), paste, collapse = ", ")) 

    # Print the vector 
    cat(out, sep = "\n") 
    } else{ 
    print("No Matches Found") 
    } 

} 

# Create matrices to compare 
A <- matrix(c(1,2,3,2,2,3,5,7,3,5,7,5,4,6,8,4,5,7,1,3), nrow = 4) 
B <- matrix(c(1,2,3,5,2,4,5,8,4,1,7,9,5,3,9,2,6,7,8,6), nrow = 4) 

# Compare matrices 
find.matches(A, B, 4) 
関連する問題