Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing Values in Randomly Generated Matrix with Additional Random Numbers

Tags:

r

I'm working with a matrix where I need to replace values coded as 1 with new randomly generated numbers

The starting point is a matrix like this

set.seed(38921)
p <- matrix(nrow = 10, ncol = 25)
for(i in 1:10){
  p[i, seq(1, floor(runif(1, min = 1, max = 25)), 1)] = 1
}

In the resulting p matrix, on each row I need the value of 1 to be replaced with a randomly generated integer bound between 1 and 25, where the numbers cannot repeat.

For example, on the first row of the matrix, there should be 6 randomly drawn numbers between 1 and 25, where none of the numbers are repeated, and 19 NA columns. On row two, there should be 12 randomly drawn numbers between 1 and 25 with no repeats and 13 NA columns.

Any help is greatly appreciated.

like image 260
medsocgrad Avatar asked Mar 28 '26 06:03

medsocgrad


1 Answers

You can simply multiply your matrix by another matrix of random numbers. NA's will remain as NA.

p*matrix(sample(1:25), 10, 25)

Or if the dimensions change:

p*matrix(sample(1:25), nrow(p), ncol(p))
like image 51
Khaynes Avatar answered Mar 29 '26 22:03

Khaynes