Home > Enterprise >  Using a loop to create different samples from the same dataset
Using a loop to create different samples from the same dataset

Time:11-15

I am trying to create different samples with a different size from the same dataset, an have them saved in a separate dataframe.

When I run the code below, I only get one dataset back with the size of the first value of n.values. Ideally I want to get 3 different datasets (results500, results1000 and results2000) with 3 different sizes (500,1000,2000).

Any idea on how to do this?

n.values=c(500,1000,2000)
for (i in n.values) {
  sample_data = sample_n(train,i)
  results <- data.frame(matrix(ncol = ncol(sample_data), nrow = i))
  results[,i]=sample_data
}

CodePudding user response:

Put it in a list:

n.values=c(500,1000,2000)
results = list()
for (i in 1:length(n.values)) {
  results[[i]] = sample_n(tbl = train, size = n.values[i], replace = TRUE)
}

Or more concisely,

results = lapply(c(500,1000,2000), sample_n, tbl = train, replace = TRUE)

You can then use results[[1]] for the first sample, etc.

  • Related