Artemis Fowl
Artemis Fowl

Reputation: 301

R populate list with samples

I have a numeric vector stock_data containing thousands of floating point numbers, I know i can sample them using

sample(stock_data, sample_size)

I want to take 100 different samples and populate them in a list of samples.

How do i do that without using a loop to append the samples to a list?

I thought of creating a list replicating the stock data 100 times then using lapply on them.

I tried:

all_repl <- as.list(rep(stock_data,100))
all_samples <- lapply(all_repl, sample, size=100)

But all_repl doesn't contain a list of data, it contains a single numeric vector which has replicated the data 100 times.

Can anyone suggest what's wrong and point out a better method to do what i want.

Upvotes: 3

Views: 996

Answers (1)

akrun
akrun

Reputation: 887148

We can use replicate

replicate(100, sample(stock_data, sample_size))

Using simplify=FALSE get the output in a list. Using a reproducible example

replicate(5, sample(1:9, 5), simplify=FALSE)

Upvotes: 3

Related Questions