2015-05-02 138 views
2

假設我們有一個矩陣,如下所示:R:列和行索引與最大值

-0.3 0.2 0.001 -0.4 0.5 
0.25 0.45 0.2 -0.001 0.02 
0.8 - 0.2 0.35 0.1  0.1 
0.25 -0.14 -0.1 0.02 0.4 

現在我想找到具有尺寸2×2和具有的最大元素矩陣的一部分(絕對值)。 所以在這裏,這將是以下指標:

2 1 
2 2 
3 1 
3 2 

因爲

0.25 0.4 
0.8 -0.2 

是具有ALL在這個矩陣的2×2矩陣的最大價值矩陣的一部分。

我該如何在R中實現它?

我做了這個小例子,因爲我的實際矩陣包含大約4000列和5000行,但在這個矩陣中的許多值幾乎爲零。這很難形象化,所以出於這個原因,我想只將可視化的最重要的。

+0

你的意思是在你想要的輸出中有0.45而不是0.4嗎? – dayne

+0

是的,它想要2×2矩陣的最大和(使用絕對值)的元素。 – Anita

+0

希望下面的幫助。 –

回答

1

您可以使用which來查找矩陣的最大值的索引。

set.seed(1234) 
mat <- matrix(sample(1:20), ncol = 5) 
mat 
#  [,1] [,2] [,3] [,4] [,5] 
# [1,] 3 14 8 20 17 
# [2,] 12 10 6 15 16 
# [3,] 11 1 7 2 19 
# [4,] 18 4 5 9 13 

which(mat == max(mat), arr.ind = TRUE) 
#  row col 
# [1,] 1 4 

如果你是在每列(或行)尋找最大可以使用:

apply(mat, 2, which.max) 
# [1] 4 1 1 1 3 

編輯時,問題澄清

mrow <- nrow(mat); mcol <- ncol(mat) 
subs <- list() 
for (i in 1:(nrow(mat) - 1)) { 
    for (j in 1:(ncol(mat) - 1)) { 
    x <- c(i, j, i, j + 1, i + 1, j, i + 1, j + 1) 
    subs[[paste0(i, j)]] <- matrix(x, ncol = 2, byrow = TRUE) 
    } 
} 

sums <- sapply(subs, function (x) sum(abs(mat[x]))) 
win <- subs[[which(sums == max(sums))]] 
mat[win[1, 1]:(win[1, 1] + 1), win[1, 2]:(win[1, 2] + 1)] 
#  [,1] [,2] 
# [1,] 20 17 
# [2,] 15 16 
+0

感謝您的回答,但這不是我的問題的確切答案。我希望矩陣墊的那一部分是一個2×2矩陣,它具有最大的值 – Anita

1

,我會非常慢但做這項工作,這將給所需的子矩陣的行和列索引:

library(magrittr) 

df = expand.grid(seq(nrow(mat)-1), seq(ncol(mat)-1)) 

vec = apply(df, 1, function(u){ 
       mat[u[1]:(u[1]+1),u[2]:(u[2]+1)] %>% 
       abs %>% 
       sum 
     }) 

ind = df[which.max(vec),] 
mat[ind[[1]]:(ind[[1]]+1),ind[[2]]:(ind[[2]]+1)] 

#  [,1] [,2] 
#[1,] 20 17 
#[2,] 15 16 

其中mat是:

mat = structure(c(3L, 12L, 11L, 18L, 14L, 10L, 1L, 4L, 8L, 6L, 7L, 
5L, 20L, 15L, 2L, 9L, 17L, 16L, 19L, 13L), .Dim = 4:5) 
2

RcppRoll提供快速滾動總和功能,可以幫助。這裏是一個答案比運行速度快於大型矩陣:

n <- matrix(rnorm(4000*5000),nrow=4000,ncol=5000) 


find_idx_max_square <- function(matrix) { 
    library(RcppRoll) 
    o <- apply(abs(matrix), 2,roll_suml,n=2L) 
    p <- t(apply(o, 1,roll_suml,n=2L)) 
    idx <- which(p == max(p,na.rm=TRUE),arr.ind=TRUE) 
    return(idx) 
} 

find_idx_max_square(n) 
     row col 
[1,] 1837 724 

> system.time(find_idx_max_square(n)) 
utilisateur  système  écoulé 
    1.863   0.159  2.023 

說明

  1. 採取矩陣matrix
  2. 計算每個列的所有後續的兩個元素爲滾動總和(matrix[i,j] + matrix[i+1,j]i in nrow(matrix) and j in ncol(matrix))。在一個新的矩陣o
  3. 計算每行上的所有隨後的兩個元件上的每個柱的(matrix[i,j] + matrix[i,j+1]incol(matrix)nrow(matrix)j)滾動總和存儲它。將它存儲在一個新的矩陣p中。
  4. p具有在每個小區中的[i,j][i,j][i+1,j][i,j+1]總和,原matrix
  5. [i+1,j+1]計算的p最大值。它給了我們具有最大和的2 * 2子矩陣的左上角的索引。