0

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)

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much. Appreciate the simplicity and clarity. Hopefully this will help out another noob someday soon :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.