1

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!

Pierre Lapointe
  • 16,017
  • 2
  • 43
  • 56
aotearoa
  • 305
  • 1
  • 7
  • 19
  • It is not very clear, do you need smth like this `dateRange = list(c('2015-01','2015-12'), c('2016-01','2016-12'))` ? – Aleksandr Ianevski Apr 12 '17 at 13:40
  • I'm sorry if I am not clear. But I want to store all the dateRange to the list called "ind" so when I access the ind[[1]] it will display the values of dateRange1 and ind[[2]] it will display the values in dateRange2. Hope this make sense. – aotearoa Apr 12 '17 at 13:46
  • How you get the multiple vectors? During that process you can generate your list. – jogo Apr 12 '17 at 13:50
  • `ind = list(c('2015-01','2015-12'), c('2016-01','2016-12'))`. and now `ind[[1]]` gives you your first range. if you need to append to the `ind` list, then just do `ind <- append(ind, list(c('2017-05','2016-12')))` – Aleksandr Ianevski Apr 12 '17 at 13:52
  • @AlexNevsky I suppose OP has many more such vectors. – jogo Apr 12 '17 at 14:13

2 Answers2

3

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?

Community
  • 1
  • 1
jogo
  • 12,469
  • 11
  • 37
  • 42
  • Thanks for looking into this. This mget fucnction would this apply also if I have several input$daterange in the dateRangeInput in SHiny R/ Just wondering. – aotearoa Apr 12 '17 at 15:55
2

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
Jake
  • 510
  • 11
  • 19