0

Using R, I want to create 10 vectors (say 10x1) and concatenate their results into a matrix (say 10x10) one at a time.

I figured that it might be most computationally-efficient to initialize an empty matrix first and then replace its values, column by column, with the vectors of interest.

This is what I tried.

# Initialize empty matrix
empty.m = matrix(nrow = 10, ncol = 10)

#Create vectors and attempt to insert them into matrix
for (i in 1:10) {
    empty.m[, i] = sample(10)
}

My attempt to insert the output of sample into the matrix empty.m does not work, yielding the following error:

Error in matrix[, 1] = vec : object of type 'closure' is not subsettable

Do you have any suggestions for what I can do to accomplish what I want, avoiding this error?

Gyan Veda
  • 6,309
  • 11
  • 41
  • 66
  • 2
    The provided code ran fine for me. See [here](http://stackoverflow.com/questions/11308367/object-of-type-closure-is-not-subsettable) for an explanation of the error you encountered. – Nick Dec 02 '13 at 19:50
  • You called it, @Nick! Thanks. – Gyan Veda Dec 02 '13 at 19:54

1 Answers1

2

A much easier way to create the matrix is replicate:

replicate(10, sample(10))

The first 10 represents the number of columns.

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
  • Thanks, Sven! I was looking for something like that function, but couldn't find it. – Gyan Veda Dec 02 '13 at 20:04
  • Sven, do you know how to do this with different sampling values for each column? I have a data frame that has different values in each of its columns and I want to sample from the respective column for each column of the matrix? – Gyan Veda Dec 02 '13 at 20:11
  • 1
    @user2932774 You can use `sapply(dat, sample)`, where `dat` is the name of your data frame. – Sven Hohenstein Dec 02 '13 at 20:13