0
votes

I need to repeat 100 times a vector of 16 numbers with some fixed numbers and some randomly created in specific spots. I created a function, but it repeats the first vector randomly generated, even the random numbers. But I need that the function sample work in every repeated vector, to obtain an array of 100 random numbers in the positions desired.

r1<- c(1,3,2,1,2,sample(1:4,1,replace=T),4,sample(1:4,1,replace=T),3,sample(1:4,1,replace=T),
 sample(1:4,1,replace=T),2,sample(1:4,1,replace=T),1,sample(1:4,1,replace=T),3)

rep.row<-function(x,n){matrix(rep(r1,each=100),nrow=100)}       
rp <- rep.row(r1)

May you help me? Thanks you,

2

2 Answers

1
votes

In your code, you create the random vector once at the beginning and then you replicate that (fixed) vector 100 times. What you need to do is repeat the random sampling in each iteration. You can e.g. do this using:

## Function to create your random vector:
createVector <- function(ii){
    r1 <- c(1, 3, 2, 1, 2, 
            sample(1:4, 1, replace = TRUE), 4,
            sample(1:4, 1, replace = TRUE), 3,
            sample(1:4, 1, replace = TRUE), 
            sample(1:4, 1, replace = TRUE), 2,
            sample(1:4, 1, replace = TRUE), 1, 
            sample(1:4, 1, replace = TRUE), 3)  
}

## Replicate 100 times:
set.seed(1234)
rp <- replicate(100, createVector())

head(rp)
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
# [1,]    1    3    2    1    2    1    4    3    3     3     3     2     4     1
# [2,]    1    3    2    1    2    1    4    1    3     3     3     2     3     1
# [3,]    1    3    2    1    2    2    4    4    3     2     4     2     2     1
# [4,]    1    3    2    1    2    1    4    1    3     2     2     2     1     1
# [5,]    1    3    2    1    2    1    4    4    3     3     4     2     4     1
# [6,]    1    3    2    1    2    2    4    2    3     2     3     2     1     1
#      [,15] [,16]
# [1,]     3     3
# [2,]     3     3
# [3,]     2     3
# [4,]     1     3
# [5,]     1     3
# [6,]     4     3
0
votes

This works - it puts NAs where you want your random numbers and then fills them in at the end.

r2 <- c(1,3,2,1,2,NA,4,NA,3,NA,NA,2,NA,1,NA,3)
rep.row <- matrix(rep(r2,each=100),nrow=100)
rep.row <- apply(rep.row,c(1,2),function(x) ifelse(is.na(x),sample(1:4,1,replace=T),x))