0

I'd like to create n vectors with the corresponding names. For example: n<-1:10 And I need to create the corresponding vectors x_1, x_2, ..., x_n . Is it possible to do it with "for" loop or whatever else ? For example:

 n=1:10
 for (i in n) {
 paste("x",n[i]) <- 1:9
}

The example doesn't work, but that's what I'd need to get. Thank you for your suggestions!

Eugene
  • 85
  • 8
  • 2
    Try running `length(10)` and `1:length(10)` in your console to see one issue. – Gregor Thomas Mar 08 '22 at 21:06
  • 3
    Generally, creating sequentially named variables is Bad Practice. See my answer at [How to make a list of data frames?](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames/24376207#24376207) for examples and discussion. If you really want to do this bad idea, you need to use `assign()` to assign a value to a name defined in a string. – Gregor Thomas Mar 08 '22 at 21:08
  • Thank you, Gregor. 1:length(n) was meant – Eugene Mar 08 '22 at 21:09
  • 1
    Even then, you have `n = 10`, so `1:length(n)` is the same as `1:length(10)` and is not what you intend. Run those lines in the console. – Gregor Thomas Mar 08 '22 at 21:12
  • assign works for the goal, thank you! – Eugene Mar 08 '22 at 21:13
  • Agree, thank you! Fixed it to for (i in n) – Eugene Mar 08 '22 at 21:16
  • Try `for(i in n) { print(i) }`. It's also not great. Try `for(i in 1:n)` or `for(i in seq_len(n))` – Gregor Thomas Mar 08 '22 at 21:32

1 Answers1

1

Try this with the understanding that it may cause more problems than you realize:

ls()
# character(0)
Vars <- paste("x", 1:10, sep="_")
Vars
#  [1] "x_1"  "x_2"  "x_3"  "x_4"  "x_5"  "x_6"  "x_7"  "x_8"  "x_9"  "x_10"
x <- sapply(Vars, assign, value=1:9, envir=environment())
ls()
#  [1] "Vars" "x"    "x_1"  "x_10" "x_2"  "x_3"  "x_4"  "x_5"  "x_6"  "x_7"  "x_8"  "x_9" 

It is preferable to create the vectors within a list structure (data frame or list):

X <- replicate(10, list(1:9))
names(X) <- Vars
str(X)
# List of 10
#  $ x_1 : int [1:9] 1 2 3 4 5 6 7 8 9
#  $ x_2 : int [1:9] 1 2 3 4 5 6 7 8 9
#  $ x_3 : int [1:9] 1 2 3 4 5 6 7 8 9
#  $ x_4 : int [1:9] 1 2 3 4 5 6 7 8 9
#  $ x_5 : int [1:9] 1 2 3 4 5 6 7 8 9
#  $ x_6 : int [1:9] 1 2 3 4 5 6 7 8 9
#  $ x_7 : int [1:9] 1 2 3 4 5 6 7 8 9
#  $ x_8 : int [1:9] 1 2 3 4 5 6 7 8 9
#  $ x_9 : int [1:9] 1 2 3 4 5 6 7 8 9
#  $ x_10: int [1:9] 1 2 3 4 5 6 7 8 9

The lapply() and sapply() functions make it easy to apply a function to all of the list parts with a single line of code. You can access the first list item with X[[1]] or X[["x_1"]].

dcarlson
  • 10,936
  • 2
  • 15
  • 18