7

我想将一组表示为向量的 n 值插入到矩阵中相应的一组位置中。实际应用涉及将一组 n 个海面温度值插入一个区域的图像中,该区域表示为尺寸为 nrow x ncol > n 的网格,我已经确定了应该接收温度值的 n 个水像素. 我遇到的问题是温度值的排序就好像它们来自列优先矩阵,而不是用于索引 R 网格的行优先排序。

这是我的意思的玩具示例。

> grid <- matrix(0,4,4)
> grid                       # define the base grid
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]    0    0    0    0
[3,]    0    0    0    0
[4,]    0    0    0    0

> temps <- c(9,9,9,9,9)     # we have 5 temperature values
> locs <- c(2,3,4,6,7)      # locations in the base grid that are water

> grid[locs] <- temps       # not really what I want - substitution in row-major order
> grid
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]    9    9    0    0
[3,]    9    9    0    0
[4,]    9    0    0    0

期望的结果是:

     [,1] [,2] [,3] [,4]
[1,]    0    9    9    9
[2,]    0    9    9    0
[3,]    0    0    0    0
[4,]    0    0    0    0

我想我可以玩转置网格,进行替换然后将其转回,但我认为会有更好的方法来解决这个问题。

4

4 回答 4

6

这里有几个选项,每个选项都适用于任意维度的矩阵:


arrayIndByRow <- function(ind, dim) {
   arrayInd(ind, rev(dim))[,2:1]
}

grid[arrayIndByRow(locs, dim(grid))] <- temps
grid
#      [,1] [,2] [,3] [,4]
# [1,]    0    9    9    9
# [2,]    0    9    9    0
# [3,]    0    0    0    0
# [4,]    0    0    0    0

f <- function(ind, dim) {
    nr <- dim[1]
    nc <- dim[2]
    ii <- ind - 1
    ((ii %/% nc) + 1) + nr*(ii %% nc)
}

grid[f(locs, dim(grid))] <- 1:5
grid
#      [,1] [,2] [,3] [,4]
# [1,]    0    1    2    3
# [2,]    0    4    5    0
# [3,]    0    0    0    0
# [4,]    0    0    0    0
于 2014-11-06T03:46:22.010 回答
3

一种方法是使用所需数据创建一个新矩阵,并指定byrow=TRUE创建时间。为此,您必须创建一个中间向量来存储和修改 的数据grid

grid <- matrix(rep(0,16),ncol=4)
##
temps <- c(9,9,9,9,9)     
locs <- c(2,3,4,6,7)      
##
#vgrid <- as.numeric(grid)
vgrid <- c(grid)
vgrid[locs] <- temps
##
> matrix(vgrid,ncol=ncol(grid),byrow=TRUE)
     [,1] [,2] [,3] [,4]
[1,]    0    9    9    9
[2,]    0    9    9    0
[3,]    0    0    0    0
[4,]    0    0    0    0
于 2014-11-05T21:38:05.023 回答
3

如果你有一个方阵,你可以编写一个小模函数,用正确的数字替换你的数字:

new_num <- function(x,num_rows){
  x = x - 1
  row    <- x %/% num_rows
  column <- x %% num_rows
  newnum <- column * num_rows + row + 1
  return(newnum)
}

temps <- c(9,9,9,9,9)     
locs <- c(2,3,4,6,7)

new_locs <- new_num(locs,4)

M <- matrix(0,4,4)
M[new_locs] <- temps

你也可以用非方阵来做到这一点,只是有点难。

于 2014-11-05T23:34:28.487 回答
3

你可以对索引做一些工作。首先,我们通过列数制作一个矩阵长度的序列。然后我们迭代地将 1 添加到序列中。我们对行数这样做。然后将该向量子集为位置向量将为我们提供矩阵中的位置。

x <- seq(1, length(grid), ncol(grid))
grid[sapply(0:(nrow(grid)-1), "+", x)[locs]] <- temps
grid

#      [,1] [,2] [,3] [,4]
# [1,]    0    9    9    9
# [2,]    0    9    9    0
# [3,]    0    0    0    0
# [4,]    0    0    0    0
于 2014-11-06T00:39:41.740 回答