aotearoa
aotearoa

Reputation: 315

Store multiple vectors in a list using for-loop

I'm new to R. I have multiple vectors which I want to store in a list in a for loop. I've tried using [], [[]] and () and I am getting an error stating that dateRange not found. Can you please help and fix my code?

dateRange1 <- c('2015-01','2015-12')
dateRange2 <- c('2016-01','2016-12')
ind <- list()

for (a in 1:2) {
  ind[a] <- dateRange(a)
 }

ind

Thanks and have a great day!

Upvotes: 1

Views: 2795

Answers (2)

jogo
jogo

Reputation: 12569

If you really want that, use get() or mget()

ind <- mget(paste0("dateRange", 1:2))

Normaly you get such a bunch of vectors if you used assign() somewhere before. That is the point where you have to restructure your process of data generation. (Normaly the use of assign() is not a good idea. "If the question is: use assign()? the answer almost is: no").
Why is using assign bad?

Upvotes: 3

Jake
Jake

Reputation: 520

You don't have an object called dateRange. To do what you're trying to need to use eval and parse. Set a <- 1 then run pieces individually to see what they do. Check to see what paste0("dateRange", a) does, then parse(text = paste0("dateRange", a)), then eval(parse(text = paste0("dateRange", a))).

dateRange1 <- c('2015-01','2015-12')
dateRange2 <- c('2016-01','2016-12')
ind <- list()

for (a in 1:2) {
  ind[[a]] <- eval(parse(text = paste0("dateRange", a)))
}

ind

Upvotes: 2

Related Questions