Search code examples
rmatrixreplacesample

Sampling with replacement a matrix element from a list in R


Here I am generating a list of matrix objects.

c<-11
l<-10
v<-list()
p<-100

for(i in 1:p) {
m<-matrix(sample(c(-1,1),l*c,replace=TRUE),l,c)
v[[i]]<-m
}

At this point, I am trying to randomly sample with replacement a matrix element from the list vector 'v'.

sample(v,size=11,replace=TRUE)

But this sample function returns the first 11 elements, instead of randomly selecting from the 100 elements in 'v'.

First, how do I randomly select matrix objects from 'v' and store those random samples in a new object?


Solution

  • If we want to sample from each element of the list 'v' use sapply to loop over the list

    out <- sapply(v, function(x) sample(x, size = 11, replace = TRUE))
    

    or if you want to sample 11 list elements, sample from the sequence of list, and use that index to extract the list elements

    out <- v[sample(seq_along(v), 11, replace = TRUE)]