Diego Jimeno
Diego Jimeno

Reputation: 312

populating matrices in R

I'm trying to populate a matrix with a randomly distributed set of values with runif , but it seems the seed is not changing for vectorized operations(I don't know if I far way mistaken at this point), so, I want for example create a matrix mxn as from one of mx1

  set <- matrix(nrow=10, ncol=1, b=T)

         [,1]
 [1,]   NA
 [2,]   NA
 [3,]   NA
 [4,]   NA
 [5,]   NA
 [6,]   NA
 [7,]   NA
 [8,]   NA
 [9,]   NA
[10,]   NA

Now I want to populate with R1 vectors(1x3) each row, (the first coordinate is constant), so I did:

cbind(set, 1, runif(1, -5, 5), runif(1, -5, 5))[,2:4]
      [,1]      [,2]     [,3]
 [1,]    1 0.3733975 3.968388
 [2,]    1 0.3733975 3.968388
 [3,]    1 0.3733975 3.968388
 [4,]    1 0.3733975 3.968388
 [5,]    1 0.3733975 3.968388
 [6,]    1 0.3733975 3.968388
 [7,]    1 0.3733975 3.968388
 [8,]    1 0.3733975 3.968388
 [9,]    1 0.3733975 3.968388
[10,]    1 0.3733975 3.968388

But as you can see, it initializes every time to the same number

I also tried:

apply(set,1, function(x){ c(1,runif(2,-5,5)) })

          [,1]      [,2]     [,3]       [,4]       [,5]      [,6]     [,7]      [,8]       [,9]     [,10]
[1,]  1.000000  1.000000 1.000000  1.0000000  1.0000000  1.000000  1.00000  1.000000  1.0000000 1.0000000
[2,] -1.932621  3.939935 4.311493 -1.5389568 -0.8101092  2.414381  3.65576 -3.048565  0.4321976 0.8809179
[3,]  2.473342 -1.889638 1.506515  0.4796991 -4.0810869 -3.723647 -2.55024  4.577043 -0.5506893 1.2699766

But it populates actually the other way around, not as expected as the MARGIN says (by row) This is actually not a big deal, because you can just transpose it, but I'd wanna know whether is a direct way to avoid such workaround. Cheers

Upvotes: 0

Views: 1130

Answers (2)

Luca Massaron
Luca Massaron

Reputation: 1809

You could initialize the matrix in this way:

nrows <- 10
ncols <- 15
matrix(runif(nrows * ncols ),nrows,ncols)

Upvotes: 5

IRTFM
IRTFM

Reputation: 263481

Shouldn't that be:

cbind(set, 1, runif(nrow(set), -5, 5), runif(nrow(set), -5, 5))[,2:4]

The R habit of automatically extending column vectors to fill unpopulated locations in the cbind and data.frame methods does not re-evaluate the expressions. It just recycles any existing values.

Upvotes: 2

Related Questions