Instead of creating 3 (or more) vectors in the .GlobalEnv
, the best practice is to keep them in a list. Imagine that the values come from a function, such as the function valores
.
valores <- function(x, max.length = 10){
n <- sample(max.length, 1)
rnorm(n, mean = x)
}
You can create the vectors in two ways.
1. lapply
set.seed(1234)
lista_vetores <- lapply(1:3, valores)
names(lista_vetores) <- paste0("vetor_", seq_along(lista_vetores))
lista_vetores
#$vetor_1
#[1] 1.6782714 2.0295630 -0.7295285 -1.2043481 1.5431729
#
#$vetor_2
#[1] 0.3709065
#
#$vetor_3
# [1] 4.241754 3.782777 3.048121 1.524600 3.435762 2.929530 3.111197
# [8] 4.273505 2.506616 4.260114
Now either way is equivalent.
lista_vetores[[1]]
lista_vetores[["vetor_1"]]
lista_vetores$vetor_1
[1] 1.6782714 2.0295630 -0.7295285 -1.2043481 1.5431729
2. cycle for
set.seed(1234)
lista_vetores_2 <- vector("list", 3)
for(i in 1:3){
lista_vetores_2[[i]] <- valores(i)
}
names(lista_vetores_2) <- paste0("vetor_", seq_along(lista_vetores_2))
identical(lista_vetores, lista_vetores_2)
#[1] TRUE
Buenas Marcus, I’m unwinding here, I already give feedback. Tks!
– Fabiano Briao
All the examples worked well. Thank you!
– Fabiano Briao