Tom
Tom

Reputation: 2351

Creating a loop, which picks up where the previous stopped

The reason for this question, is that I need to download data for which there is a daily download limit. I am trying to write a loop that picks up with downloading where it left off (for the next day).

I created the following example, in which I replaced the download function with a simple index (item_list[i+amount_done]):

# data = a list, to be filled with all the downloads
data = list()

# Yesterday, I did one list item, so the amount done is 1
data[[1]] <- "1"
amount_done <- length(data)

# The list of items that need to be downloaded
item_list <- c("1", "2", "3", "4")

# The loop I created to pick up where it stopped
for (i in (1+amount_done):length(item_list)){
  data[[i+amount_done]] <- item_list[i+amount_done] # This is where the download function would be using the index as used in this example.
  print(data[[i+amount_done]])
}

Somehow, this is the outcome:

enter image description here

The desired result is simply

data[[1]] 
"1"
data[[2]] 
"2"
data[[3]] 
"3"
data[[4]] 
"4"

What am I doing wrong here?

Upvotes: 0

Views: 46

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389135

i is the correct index that you want to use in the loop.

data = list()

# Yesterday, I did one list item, so the amount done is 1
data[[1]] <- "1"
amount_done <- length(data)

# The list of items that need to be downloaded
item_list <- c("1", "2", "3", "4")

# The loop I created to pick up where it stopped
for (i in (1+amount_done):length(item_list)){
  data[[i]] <- item_list[i] 
  print(data[[i]])
}

data

#[[1]]
#[1] "1"

#[[2]]
#[1] "2"

#[[3]]
#[1] "3"

#[[4]]
#[1] "4"

Upvotes: 2

Related Questions