Home > Blockchain >  how to create n vectors in R
how to create n vectors in R

Time:03-11

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!

CodePudding user response:

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"]].

  • Related