Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill matrix with random numbers in R?

Tags:

r

matrix

expand.grid(i=rexp(5,rate=0.1)) 

It creates just one col but is there some way to multiply this easily to 5 cols? I mean the matlab-way-of-doing-things like rand('exp', 0.1, 10,20) (creating a matrix with exponentially-distributed-random-numbers with mean 0.1 of size 10x20), how?

like image 937
hhh Avatar asked Feb 14 '12 18:02

hhh


People also ask

How do I add values to a matrix in R?

How to modify a matrix in R? We modify the R matrix by using the various indexing techniques along with the assignment operator. We can add a row or column by storing the new row/column in a vector and using the rbind() or cbind() functions to combine them with the matrix.

How do I generate a random number from a normal distribution in R?

If we want to generate standard normal random numbers then rnorm function of R can be used but need to pass the mean = 0 and standard deviation = 1 inside this function.

How do I create a custom matrix in R?

To create a matrix in R you need to use the function called matrix(). The arguments to this matrix() are the set of elements in the vector. You have to pass how many numbers of rows and how many numbers of columns you want to have in your matrix. Note: By default, matrices are in column-wise order.


2 Answers

Use the matrix function:

matrix(rexp(200, rate=.1), ncol=20) 

ETA: If you want to do it without repeating the 200, you can define a function to do so:

fill.matrix = function(expr, nrow=1, ncol=1) {     matrix(eval(expr, envir=list(x=nrow*ncol)), nrow=nrow, ncol=ncol) }  fill.matrix(rexp(x, rate=.1), nrow=10, ncol=20) 

The x thus becomes the dummy variable you're talking about. Is that what you're looking for?

like image 138
David Robinson Avatar answered Oct 17 '22 02:10

David Robinson


you can do something like:

matrix(rexp(200), 10) 

And of course use what ever distribution you want.

like image 36
Stedy Avatar answered Oct 17 '22 03:10

Stedy