pabrother
pabrother

Reputation: 1

How to create multiple vectors by using loop

May I know how I can create multiple vector in R. For example, if I want to create 10 vectors (v1~v10) and tried

for (i in 1:10)) {
paste('v',i sep = "", collapse = NULL) <- vector()
}

But it seems it can't work, can you advise how I can do this ?

Thank you

Upvotes: 0

Views: 424

Answers (2)

Rui Barradas
Rui Barradas

Reputation: 76673

The easiest way is with replicate and setNames. The lapply uses the new (R 4.1.0) lambdas. Then, assign to the global environment in one instruction.

v <- setNames(replicate(10, vector()), paste0("v", 1:10))
#setNames(lapply(1:10, \(x) vector()), paste0("v", 1:10))
list2env(v, envir = .GlobalEnv)
ls()
# [1] "v1"  "v10" "v2"  "v3"  "v4"  "v5"  "v6"  "v7"  "v8"  "v9" 
#[11] "x"

A one-liner is

list2env(setNames(replicate(10, vector()), paste0("v", 1:10)), envir = .GlobalEnv)

Upvotes: 1

Vin&#237;cius F&#233;lix
Vin&#237;cius F&#233;lix

Reputation: 8826

If you want to create 10 empty vectors, you can use the command assign

for (i in 1:10) {
  assign(paste('v',i, sep = "", collapse = NULL),vector()) 
}

Upvotes: 0

Related Questions