Search code examples
rloopsapplyreplicaterep

Is there a way to repeat a function on a whole dataset n times in R?


Feels like this is a super basic question but I'm a bit stuck.

Let's say I have a dataset of 100 items:

    x <- rnorm(100, 0, 1)

I want to generate a new object which consists of x shuffled 10,000 times using sample(x, size=100, replace=F). As in, what I want to end up with isn't these repeats all shuffled together but so that each item in x has to appear once before any can appear twice, etc.

I feel like this ought to be super simple but can't think what to do? My first thought was rep() but that gives me the same shuffling n times, and I want each shuffle to be independent. I tried

        repeat{ 
        sample(x, size=100, replace=F)
        i <- i + 1
        if (i == n){
        break
        }
        }

but that's incredibly slow even for a small number of repeats. Also thought about apply family but seems like they're intended to repeat a command for every item in a list, not do something to the entire list a number of times? (please correct me if that's wrong!)

I'd v much appreciate any help!


Solution

  • Answer derived from comments to question:

        reps <- as.vector(replicate(sample(x, replace = F, size = length(x)), n = 10000, simplify = F)
    

    And then to convert it to a more usable format,

        reps <- as.numeric(unlist(reps))