1

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!!

Lola1993
  • 151
  • 6

1 Answers1

1

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)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Hi Akrun! It does not really work, when i run your for loop, I only get in. my global environment a single variable which is 'e_' . Ok for your second approach, but how do i 1. Call each element of the list e_1, e_2 ... and then how do i put them in my dataframe as columns? – Lola1993 Jul 20 '21 at 16:44
  • @Lola1993 sorry, I didn't check your `sprintf` command. Updated. It should be `'e_%d'` as `t` is numeric – akrun Jul 20 '21 at 16:45
  • 1
    Ahhh ok !!! Thank you so much! But i actually really like your advice of not saving everything in global environment, I think that is much better. – Lola1993 Jul 20 '21 at 16:46
  • Would you have any way to name all the elements of the list by having a sprint f or something? – Lola1993 Jul 20 '21 at 16:46
  • @Lola1993 Regarding the second option with `list`, you can loop over the `list` with `lapply` if you want to do some operations i.e. `lapply(lst1, yourfun)` – akrun Jul 20 '21 at 16:46
  • Updated. `sprintf` is vectorized. So you can do as `names(lst1) <- sprintf('e_%d', periods)` or with `paste0` ie. `paste0('e_', periods)` – akrun Jul 20 '21 at 16:47