rrandomtidyversesimulationuniform

Loop over to create new variables from uniform dataframe


My problem is the following

I want to create variables e_1, e_2, e_3, ... , e_50 which are all composed of 100 draws from the uniform[-1,1]

This means e_1 is a vector of 100 draws from U[-1.1], e_2, .., e_50 as well.

Here is what I thought I could do :

periods <- c(1:50)
people <- c(1:100)
for (t in periods){
sprint('e_', t) <- runif(100, -1,1)
}

This did not work, and i am really not sure how to change it to obtain what I want.

Thank you so much for your help!!


Solution

  • It is better not to create objects in the global environment. Regarding the issue in the code, the assignment should be based on assign

    for(t in periods) {
        assign(sprintf('e_%d', t), runif(100, -1, 1))
    }
    

    An approach that wouldn't create multiple objects in the global env, would be to create a list with replicate

    lst1 <- replicate(length(periods), runif(100, -1, 1), simplify = FALSE)
    names(lst1) <- sprintf('e_%d', periods)