statistics - Merging matrix index in R -


i have dataset (x) contains

 1 10 20 30 34 38 59 83 ... 

i have big matrix nx1. want assign value 1 each row in x. example

mat[1:10,1] = 1  mat[20:30,1] = 1 etc... 

in r, size of x quite big , takes while following:

for ( j in 1:dim(x)[1] ) {      mat[x[j,1]:x[j,2], 1] <- 1  } 

please me if there faster way this. thanks.

you can make list of rows want assign value of 1 in big matrix, using apply on x seq.int row numbers this...

rows <- unlist( apply( x , 1 , fun = function(x){ seq.int(x[1],x[2])}) ) rows #  [1]  1  2  3  4  5  6  7  8  9 10 20 21 22 23 24 25 26 27 28 29 30 34 35 36 37 38 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 

and use subsetting faster, this

mat[ rows , 1 ] <- 1 

Comments