0

I'm new to R and I am having some trouble. I created 10 samples(s1..s10) of random numbers

for(i in 1:numOfsam) {
    assign(paste("s",i,sep=""),rnorm(length,mu,sigma))

smp<-c(s1,s2,s3,s4,s5,s6,s7,s8,s9,s10)

I want to assign this samples to a vector, but it must be done in loop due to the number of samples can be larger.

1 Answer 1

4

Do not use assign until you are an experienced R programmer (and then you will need it very rarely). Here you could pre-allocate a matrix and fill it. The columns will correspond to your samples:

numOfsam <- 3
length <- 5
mu <- 2
sigma <- 0.1

result <- matrix(nrow = length, ncol = numOfsam)
set.seed(42) #for reproducibility
for (i in seq_len(numOfsam)) {
  result[,i] <- rnorm(length, mean = mu, sd = sigma)
}
result
#         [,1]     [,2]     [,3]
#[1,] 2.137096 1.989388 2.130487
#[2,] 1.943530 2.151152 2.228665
#[3,] 2.036313 1.990534 1.861114
#[4,] 2.063286 2.201842 1.972121
#[5,] 2.040427 1.993729 1.986668

Of course you can get exactly the same result without a for loop:

set.seed(42) #for reproducibility
result2 <- matrix(rnorm(length * numOfsam, mean = mu, sd = sigma), ncol = numOfsam)
result2
#         [,1]     [,2]     [,3]
#[1,] 2.137096 1.989388 2.130487
#[2,] 1.943530 2.151152 2.228665
#[3,] 2.036313 1.990534 1.861114
#[4,] 2.063286 2.201842 1.972121
#[5,] 2.040427 1.993729 1.986668
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.