2

I would like to generate dynamic (with an index number from the loop) and invoke it later like below:

for (i in seq(1,10)) {
 p_i <- i^2 #here _i is a dynamic value which is equate to the current i value
 d_i <- (p_i-20)*15 # here _i for both d_i and p_i are all dynamic
 }

Thank you very much for your expertise

East Liu
  • 107
  • 2
  • You don't need a loop. `i <- 1:10; p <- i^2; d <- (p-20)*15` will give you all results in a vector and you only need to subset this vector to extract its elements. – Roland Mar 04 '19 at 09:41
  • 2
    @RLave Please do not even mention that function to newbies. They do not need to know it exists. – Roland Mar 04 '19 at 09:42
  • my case is a much more complicated than the example i put here, could you please give more details how to achieve creating and invoking it dynamically? – East Liu Mar 04 '19 at 09:47
  • @EastLiu `myvector <- numeric(10); for (i in 1:10) {...; myvector[[i]] <- ...}` Use a list if your data cannot be stored in a vector. – Roland Mar 04 '19 at 09:52
  • @Roland. I think it is better to explain why `assign` is the worst solution and why we need to use a structure that is made to avoid artifical indexes in the environment. – Clemsang Mar 04 '19 at 09:57
  • Here why `assign` would be bad: https://stackoverflow.com/questions/17559390/why-is-using-assign-bad – RLave Mar 04 '19 at 10:00
  • @Clemsang This makes an assumption about readers that unfortunately often is not valid. I suspect that OP is happily using your `assign` code right now. The warning is ignored too often. – Roland Mar 04 '19 at 11:27
  • @Roland I does not use R very often, so some conceptions are quite hard for me to follow, but i really appreciate it all your efforts and kind reminders. I really do, the world need people like you guys to make it move on and towards better. – East Liu Mar 04 '19 at 13:12

1 Answers1

0

Here is the answer that works but I would not use as it is not a good practice to recreate an artificial structure, use vectors or lists instead.

for (i in seq(1,10)) {
  assign(paste0("p_", i), i^2)
  assign(paste0("d_", i), (get(paste0("p_", i))-20)*15)
}

I would use the vectorized solution using index to access what you want :

p <- (1:10)^2
d <- (p-20)*15
Clemsang
  • 5,053
  • 3
  • 23
  • 41