Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/65869271/how-can-i-generate-and-name-10-000-vectors-automatically-in-r-programming

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...