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!

Answers


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


Need Your Help

deserialize dynamic object

c# json rest facebook-c#-sdk

I am having a lot of trouble trying to figure out how to deserialize my response from making calls to facebook api. my c# code looks like this:

Entity Framework Unique Validation on Local and Database

entity-framework entity-framework-6

Currently I am trying to handle unique validation for entities as part of my ValidateEntity method on my DbContext. The problem I am trying to solve is when adding multiple entities at the same time

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.