Fumia
Fumia

Reputation: 35

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?

Upvotes: 1

Views: 403

Answers (2)

Vin&#237;cius F&#233;lix
Vin&#237;cius F&#233;lix

Reputation: 8811

If I understood correctly, you could sample the index

v[sample(1:p,size = c,replace = TRUE)]

Upvotes: 2

akrun
akrun

Reputation: 887108

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)]

Upvotes: 1

Related Questions