Reputation: 5413
I am defining the basic matrix:
1 2 3 4
5 6 7 8
As follows:
PROC IML;
RESET NOPRINT;
matrix = {1 2 3 4, 5 6 7 8};
EXIT:
I'm looking to resample each row with replacement so we generate matrices like:
1 3 4 2
6 6 5 5
and
1 1 3 2
5 6 6 8
How can this be done?
Note that if you're not aligned with stats, to resample with replacement means if we have a set of data:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
and wish to resample with replacement, we randomly pick 10 objects from the set to form a new 10-element set, and we're allowed to pick an element more than once (so the set {1, 1, 1, 1, 1, 1, 1, 1, 1, 1} is just as likely as any other.
Upvotes: 0
Views: 1191
Reputation: 1511
Not sure whether this is what you want. It's a simple program to select random elements from the original matrix. Replace x with any matrix you want.
proc iml;
x = {1 2 3 4, 5 6 7 8};
y= j(nrow(x),ncol(x),.);
do i=1 to nrow(x);
do j=1 to ncol(x);
y[i,j]=x[int(1+(nrow(x)-1)*ranuni(0)),int(1+(ncol(x)-1)*ranuni(0))];
end;
end;
print y ;
quit;
Upvotes: 0
Reputation: 1210
As @Itzy says, you can do this row-wise. A more efficient way is to generate all the indices (random numbers in 1:ncol(matrix)) at once and then directly index into the matrix to extract the values:
u = j(nrow(x),ncol(x));
call randgen(u, "Uniform"); /* u~U[0,1] */
k = ceil( ncol(x)*u ); /* k ~ U{1,2,3,4} */
y = shape(x[k], nrow(x), ncol(x)); /* suscript and reshape */
In addition to the blog post @Itzy mentioned, you might want to read "How to generate random numbers in SAS"
Upvotes: 0
Reputation: 11765
I'm not great with IML, but the most efficient approach would be to generate a new matrix that has in each row an integer in 1,...,k
where k
is the number of variables (4 in your case). You can then use this matrix to reshuffle the elements of your existing matrix.
This approach is shown in this blog post, except you'll have to modify it to work on your whole matrix -- in his code, the input is a row vector.
Upvotes: 1
Reputation: 949
You might be able to use the UNIFORM and INT functions to generate this, assuming that you are looking for relatively random integers between 0 and 9 in your result matrices. Note that the UNIFORM function will use the first element in your matrix as the seed, so you will need to specify a different matrix to get a different sample.
PROC IML;
RESET NOPRINT;
matrix = {1 2 3 4, 5 6 7 8};
matrix_uniform = uniform(matrix);
matrix_int_1 = int(matrix_uniform*10);
matrix_uniform = uniform(matrix_int_1);
matrix_int_2 = int(matrix_uniform*10);
print matrix_int_1;
print matrix_int_2;
EXIT:
Upvotes: 0