TheGoat
TheGoat

Reputation: 2877

Insert an element to a variable size matrix at specific locations in R Studio

I have a matrix called sectorCoor which contains a list of 18 lat long coordinates. These 18 coordinates are dependent upon another variable which could change the size of the matrix from a minimum of 6 to a maximum of 36. The matrices will always be a multiple of 6. So depending upon the size of the sectorCoor matrix I would like to divide the existing matrix into elements of size 6 and from there I would like to add the variable siteCoor to the very start of the sectorCoor matrix and again after the first 6 elements, add siteCoor and take the next 6 and so on and so on until all multiples of 6 have been completed.

Suggestions are greatly appreciated.

 siteCoor, 
 first 6 lon lat coordinates
 siteCoor
 siteCoor
 Next 6 lon lat coordinates
 siteCoor
 siteCoor
 Next 6 lon lat coordinates
 siteCoor

> siteCoor
         [,1]     [,2]
[1,] 152.7075 -27.7027

> sectorCoor
           lon       lat
 [1,] 152.7075 -27.70270
 [2,] 152.6983 -27.68203
 [3,] 152.7028 -27.68085
 [4,] 152.7075 -27.68046
 [5,] 152.7122 -27.68085
 [6,] 152.7167 -27.68203
 [7,] 152.7209 -27.68394
 [8,] 152.7322 -27.70592
 [9,] 152.7311 -27.71000
[10,] 152.7291 -27.71382
[11,] 152.7264 -27.71724
[12,] 152.7230 -27.72015
[13,] 152.7190 -27.72243
[14,] 152.6920 -27.72015
[15,] 152.6886 -27.71724
[16,] 152.6858 -27.71382
[17,] 152.6839 -27.71000
[18,] 152.6828 -27.70592
[19,] 152.6825 -27.70173

Upvotes: 0

Views: 87

Answers (1)

bgoldst
bgoldst

Reputation: 35324

I would preallocate a matrix of the correct size, and separately populate the siteCoor and sectorCoor rows. We can use the initial data vector passed to matrix() to populate the siteCoor rows, and then use an index-assignment to populate the sectorCoor rows.

res <- matrix(siteCoor,nrow(sectorCoor)+nrow(sectorCoor)%/%6L*2L,2L,byrow=T);
res[c(F,rep(T,6L),F),] <- sectorCoor;
res;
##       [,1] [,2]
##  [1,]   -1   -2
##  [2,]    1   19
##  [3,]    2   20
##  [4,]    3   21
##  [5,]    4   22
##  [6,]    5   23
##  [7,]    6   24
##  [8,]   -1   -2
##  [9,]   -1   -2
## [10,]    7   25
## [11,]    8   26
## [12,]    9   27
## [13,]   10   28
## [14,]   11   29
## [15,]   12   30
## [16,]   -1   -2
## [17,]   -1   -2
## [18,]   13   31
## [19,]   14   32
## [20,]   15   33
## [21,]   16   34
## [22,]   17   35
## [23,]   18   36
## [24,]   -1   -2

In the above I use a short logical vector to subscript the sectorCoor rows of res. R recycles the vector across the entire row size of res, achieving the required periodicity of the storage pattern.

Data

N <- 3L;
sectorCoor <- matrix(seq_len(N*6L*2L),ncol=2L);
siteCoor <- matrix(c(-1,-2),ncol=2L);

Upvotes: 1

Related Questions