Wednesday 15 September 2010

r - How can I insert the values from a vector into a matrix using column-major order? -



r - How can I insert the values from a vector into a matrix using column-major order? -

i want insert set of n values expressed vector corresponding set of locations in matrix. real-world application involves inserting set of n sea surface temperature values image of part represented grid dimension nrow x ncol > n in have identified n water pixels should receive temperature values. problem i've run temperature values ordered if column-major matrix rather row-major ordering used index r grid.

here toy illustration of mean.

> grid <- matrix(0,4,4) > grid # define base of operations 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) # have 5 temperature values > locs <- c(2,3,4,6,7) # locations in base of operations grid water > grid[locs] <- temps # not 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

the desired result rather:

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

i suppose play transposing grid, doing substitution , transposing back, i'd think there improve way approach problem.

here couple of options, each of works on matrices of arbitrary dimension:

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

r matrix-indexing

No comments:

Post a Comment