JS_joy
JS_joy

Reputation: 21

How can I generate and name 10,000 vectors automatically in R programming?

I have a vector that has 10,000 elements(natural numbers). The vector is, say, End.Num. I want to generate and name 10,000 new vectors using this vector as below.

NewVec1 <- 1:End.Num[1]
NewVec2 <- 1:End.Num[2]
NewVec3 <- 1:End.Num[3]

NewVec9999 <- 1:End.Num[9999]
NewVec10000 <- 1:End.Num[10000]

How can I this without writing 10,000 lines in R? Thanks for your attention.

Upvotes: 2

Views: 118

Answers (1)

Leonardo
Leonardo

Reputation: 2485

Try this:

  1. Define a function

    vec <- function(x) {
      v <- 1:x
    }
    
  2. Generate a list of vectors

    the_list <- lapply(End.Num, FUN = vec)
    
  3. Split the_list in n variables

    list2env(setNames(the_list,paste0("v",seq_along(the_list))), envir = parent.frame())
    

I advise you to stop at point 2 and to access the elements of the list via the_list[[i]].

Upvotes: 6

Related Questions