-2

How can I get a function which takes a matrix and a vector as input and does the following

v<-c(1,2,4)
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

The outout shall be:

     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    2    5
[4,]    3    6
[5,]    3    6
[6,]    3    6
[7,]    3    6
RHertel
  • 23,412
  • 5
  • 38
  • 64
sdji
  • 1
  • 4

1 Answers1

1

You can use rep to replicate the rows of the matrix ('m1') by the vector ('v')

m1[rep(1:nrow(m1), v),]
#     [,1] [,2]
#[1,]    1    4
#[2,]    2    5
#[3,]    2    5
#[4,]    3    6
#[5,]    3    6
#[6,]    3    6
#[7,]    3    6

data

m1 <- matrix(1:6, ncol=2)
v<-c(1,2,4)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • @sdji You showed a matrix and a vector. Are you getting the same error using the data I used? – akrun Jul 25 '15 at 07:12
  • get Error: long vectors not supported yet: ../../src/include/Rinlinedfuns.h:137 ..is there a way to do this on really really larg matri with 10 millions row – sdji Jul 25 '15 at 07:14
  • @sdji Which version of R are you using? I am using the `R 3.2.1` – akrun Jul 25 '15 at 07:15
  • me too also using that version..is there a package or is it doble with MATRIX.. – sdji Jul 25 '15 at 07:17
  • mean the package matrix with the capital m – sdji Jul 25 '15 at 07:17
  • 1
    @sdji In the question, you posted a minimal example and expected output. My answer was based on that. It didn't mention anything about how big the dataset is. – akrun Jul 25 '15 at 07:18
  • 1
    I can't confirm the error message. When I tested @akrun's solution it produced the desired output. – RHertel Jul 25 '15 at 07:19
  • @sdji Using the same example, worked with `Matrix` also. `m2 <- Matrix(1:6, ncol=2);m2[rep(1:nrow(m2), v),]# 7 x 2 Matrix of class "dgeMatrix"` – akrun Jul 25 '15 at 07:22
  • @sdji Also, if the matrix is really big, then could you split it up and then try. i.e. Just for an example `n <- 5; m2 <- m1[seq_len(n),]; m2[rep(1:nrow(m2), v[seq_len(n)]),]` and repeat this for the remaining rows and `rbind`. – akrun Jul 25 '15 at 07:27