2
votes

Suppose I have a 10 x 10 matrix. I want to randomly choose 2 numbers from each column and take the square of the difference of these numbers. I wrote the R code for that and I get 10 values, but I wish to repeat this, say, 100 times, in which case I need to get 100*10=1000 numbers. How could I do that?

x <- rnorm(100)
m <- 10 
n <- 10 
X <- matrix(x,m,n) 

for (i in 1:m ) {
y <- sample(X[,i],2,rep=F)
q2[i] <- (y[1]-y[2])^2  
}   
1
look at ?replicate - Davide Passaretti
Just wrap your for loop as a function and use replicate as @Davide Passaretti suggested - nrussell
Probably just replicate(100, sapply(data.frame(X), function(y) diff(sample(y, 2))^2)) will work - David Arenburg
@DavidArenburg, thanks. It perfectly works - Günal

1 Answers

2
votes

Or as @Davide Passaretti and @nrussell mentioned in the comments, you can use replicate

f1 <- function(x, m){
 q2 <- vector(mode='numeric', length= m)
 for(i in 1:m){
 y <- sample(x[,i], 2, rep=FALSE)
 q2[i] <- (y[1]-y[2])^2
 }
q2
}

n <- 100 
res <- replicate(100, f1(X, m))
prod(dim(res))
#[1] 1000