简体   繁体   中英

Generate Vectors With For Loop in R

Incredibly basic question. I'm brand new to R. I feel bad for asking, but also like someone will crush it:

I'm trying to generate a number of vectors with a for loop. Each with an unique name, numbered by iteration. The code I'm attaching throws an error, but I think it explains what I'm trying to do in principle fairly well.

Thanks in advance.

vectorBuilder <- function(num){
for (x in num){
  paste0("vec",x) <- rnorm(10000, mean = 0, sd = 1)}
}

numSeries <- 1:10
vectorBuilder(numSeries)

You can write the function to return a named list:

create_vector <- function(n) {
    setNames(replicate(n, rnorm(10000), simplify = FALSE), 
             paste0('vec', seq_len(n)))
}

and call it as:

data <- create_vector(10)

data will have list of length 10 with each element having a vector of size 10000. It is better to keep data in this list instead of creating lot of vectors in global environment. However, if you still want separate vectors you can use list2env :

list2env(data, .GlobalEnv)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM