A: How to create/save a vector using for and Paste?

Asked

Viewed 70 times

0

I’d like to rotate one for and save 3 different vectors with for example: vetor_1, vetor_2 and vetor_3. Each vector is receiving a different set of values. I can’t do this paste be the vector name, for example, paste("vetor_",i, sep="").

2 answers

4

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

2


You can do exactly what is asked using the function assign:

for(i in 1:3) { 
  nome <- paste("vetor_", i, sep = "")
  assign(nome, rnorm(10))
}
  • Buenas Marcus, I’m unwinding here, I already give feedback. Tks!

  • All the examples worked well. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.