Search code examples
rloopsfor-loopmatrixsequential

Sequentially amending row values in a matrix using loop in R


I don't really know how to word this question so it's easy to understand, so please bear with me.

I have a 2 column matrix and need to amend the values in column 1 according to another matrix, say h.

For example, h may look like this: h <- c(11,10,10,8,12) and my data matrix looks like:

 [1,]    0    0
 [2,]    0    0
 [3,]    0   26
 [4,]    0   44
 [5,]    0    0
 [6,]    0   65
 [7,]    0    0
 [8,]    0    0
 [9,]    0    0
[10,]    0   28
[11,]    0   25
[12,]    0    0
[13,]    0   81
[14,]    0    0
[15,]    0    0 ...

etc...

I need to rename the column of zeros, according to the item number in vector h. So I need rows 1:11 to be labelled 1, 12:21 to be labelled 2, 22:31 to be labelled 3 etc., like this:

 [1,]    1    0
 [2,]    1    0
 [3,]    1   26
 [4,]    1   44
 [5,]    1    0
 [6,]    1   65
 [7,]    1    0
 [8,]    1    0
 [9,]    1    0
[10,]    1   28
[11,]    1   25
[12,]    2    0
[13,]    2   81
[14,]    2    0
[15,]    2    0 ...

My problem is being able to specify which rows in column 1 to change. I can easily create a loop which labels the 1's, data[1:h[1],1) <- 1 but when it comes to the remaining numbers, I cannot find a way to say to R "choose the next X rows, after the ones we've already changed", "then select the next X rows and change to __".

Sorry if I haven't explained my problem too well!


Solution

  • We can use rep to replicate the sequence generated (seq_along(h)) by the elements of 'h'.

    m1[,1] <- rep(seq_along(h), h)
    

    According to ?seq

    ‘seq_along’ and ‘seq_len’ are very fast primitives for two common cases.... ‘seq_along’ and ‘seq_len’ return an integer vector