mLstudent33
mLstudent33

Reputation: 1175

how do I save samples in an array or matrix in R?

I am okay with Python, Numpy but trying R and this seemingly simple operation has me stuck in R.

This is what I have but I get a number of items to replace is not a multiple of replacement length error.

# find sample variance with n
samples <- matrix(0, nrow=num_samples, ncol=samp_size)
for(i in 1:10000){
  temp <- sample(population, samp_size, replace=TRUE)
  samples[i] = temp
}
samples[0]

I am not hung up on using matrices, can be an array or vector or list or anything but just some standard ways of doing this because searching online did not give me a quick answer for this basic operation.

Upvotes: 1

Views: 691

Answers (2)

andrew_reece
andrew_reece

Reputation: 21274

The simplest solution is just to initialize samples with your actual samples:

set.seed(123)
n_samples <- 5
n_obs <- 10
population <- letters

samples <- matrix(sample(population, n_obs*n_samples, replace=TRUE),  
                  nrow=n_samples, ncol=n_obs)

But to do it the way you've started, you just need to let R know you'd like to put entries into all columns of samples, like this: samples[i, ].

It's similar to using : syntax in Numpy: array[i, :].

samples <- matrix(0, nrow=n_samples, ncol=n_obs)

for(i in 1:n_samples){
  temp <- sample(population, n_obs, replace=TRUE)
  samples[i,] = temp
}

Either way, the output is the same:

samples
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "h"  "u"  "k"  "w"  "y"  "b"  "n"  "x"  "o"  "l"  
[2,] "y"  "l"  "r"  "o"  "c"  "x"  "g"  "b"  "i"  "y"  
[3,] "x"  "s"  "q"  "z"  "r"  "s"  "o"  "p"  "h"  "d"  
[4,] "z"  "x"  "r"  "u"  "a"  "m"  "t"  "f"  "i"  "g"  
[5,] "d"  "k"  "k"  "j"  "d"  "d"  "g"  "m"  "g"  "w"  

Upvotes: 2

Piotr Bogdanski
Piotr Bogdanski

Reputation: 23

Have you tried replicate?

samples <- t(replicate(n = num_samples, sample(population, samp_size, replace=TRUE),simplify = "array"))

This will return a matrix of the dimensions samp_size x num_samples.

Upvotes: 2

Related Questions