R:返回矩阵中最大的连续数字对

标签 r matrix

我正在尝试编写一个 R 代码来返回矩阵中最大的连续数字对。连续对可以是水平的、垂直的和两条对角线。

例如
如果我有矩阵:

ma = array(c(8,4,3,1,7,5,9,15,6,10,16,11,2,14,12,13), dim = c(4,4))

(1) 水平的最高连续对:16 和 12; (2) 垂直:16 和 11 (3) 对角线 ():16 和 13; (4) 对角线 (/):16 和 15。

我怎样才能在 R 中做到这一点?

最佳答案

这是一个使用矩阵运算的解决方案,即 比行和列上的嵌套循环更有效,尤其是在大型矩阵上。

directionalSums <- function(x){
  stopifnot(is.matrix(x))

  # padding functions to allow matrix addition
  padL  <- function(x) cbind(-Inf,x)
  padR  <- function(x) cbind(x,-Inf)
  padU  <- function(x) rbind(-Inf,x)
  padD  <- function(x) rbind(x,-Inf)

  # these padding functions are just for readability
  padLU <- function(x) padL(padU(x))
  padLD <- function(x) padL(padD(x))
  padRU <- function(x) padR(padU(x))
  padRD <- function(x) padR(padD(x))

  m <- nrow(x)
  n <- ncol(x)

  sumR <- padR( (padL(x) + padR(x))[1:m,2:n] )
  sumD  <- padD( (padU(x) + padD(x))[2:m,1:n])
  sumRD <- padRD( (padLU(x) + padRD(x))[2:m,2:n] )
  sumRU <- padRU( (padRU(x) + padLD(x))[2:m,2:n] )

  list(`right`=sumR, 
       `down`=sumD,
       `right and down`=sumRD,
       `right and up`=sumRU)

}

让我们试试看。
(sumList <- directionalSums(ma))

maxLocList <- lapply(sumList, function(x) which(x==max(x), arr.ind=TRUE))

for (i in 1:length(maxLocList) ){
  nameD <- names(maxLocList)[i]
  startCell <- maxLocList[[i]]
  maxSum <- sumList[[i]][startCell]
  x1 <- ma[startCell]
  x2 <- maxSum - x1
  writeLines(paste0('The max-sum consec. pair going ',
                    nameD, ' starts at [',
                    paste(startCell, collapse=', '),
                    '], with sum ', maxSum,
                    ' and components ', x1, ' and ',x2)
             )
}

返回:
$right
     [,1] [,2] [,3] [,4]
[1,]   15   13    8 -Inf
[2,]    9   15   24 -Inf
[3,]   12   25   28 -Inf
[4,]   16   26   24 -Inf

$down
     [,1] [,2] [,3] [,4]
[1,]   12   12   16   16
[2,]    7   14   26   26
[3,]    4   24   27   25
[4,] -Inf -Inf -Inf -Inf

$`right and down`
     [,1] [,2] [,3] [,4]
[1,]   13   17   20 -Inf
[2,]   13   21   22 -Inf
[3,]   18   20   29 -Inf
[4,] -Inf -Inf -Inf -Inf

$`right and up`
     [,1] [,2] [,3] [,4]
[1,] -Inf -Inf -Inf -Inf
[2,]   11   11   12 -Inf
[3,]    8   19   30 -Inf
[4,]   10   31   23 -Inf

The max-sum consec. pair going right starts at [3, 3], with sum 28 and components 16 and 12
The max-sum consec. pair going down starts at [3, 3], with sum 27 and components 16 and 11
The max-sum consec. pair going right and down starts at [3, 3], with sum 29 and components 16 and 13
The max-sum consec. pair going right and up starts at [4, 2], with sum 31 and components 15 and 16

关于R:返回矩阵中最大的连续数字对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41730651/

相关文章:

r - 将多列合并为一列

r - SF : Write Lat/Long from geometry into separate column and keep ID column

RDCOMClient + Outlook 电子邮件

r - 合并两个数据帧,依次获取每个数据帧的交替行

latex - 在一行中获取两个矩阵

c++ - 如何在opencv中获取矩阵的一部分

c - 矩阵中总和最大的行

R:if_else 和时区强制

r - 如何根据最终列值对矩阵中的列进行排序?

r - 对矩阵/数据框中的行组进行操作