Help with a Loop

Hello all,

I have this loop:

List = list()
while (x < 150) {
  List = test[[x]][["data"]][[1]][["count"]]


This will give me a value, and assign it to a vector called "List". However, it will replace the value before it. Is there a way to make sure all of the values are in the table?

FYI, test[[x]][["data"]][[1]][["count"]] is apart of a dataframe, so that shouldn't change.


Hey there. Just one, possibly two, simple things you need to adjust. First of all your counter, x, isn't being added to in the code you share, but if the loop isn't hanging on endlessly, perhaps you're updating the value of x in your while loop but simply forgot to add that code to this example.

But the thing that's definitely giving you a headache is that you need to assign the xth value to the xth place in List. That is, you need to have the loop write each result to List[[x]].

I've done so below. Also note that I've changed it to a for loop where x is a vector that goes from 1 to 149.

List = list()

for (x in 1:149) {
  List[[x]] = test[[x]][["data"]][[1]][["count"]]


Hope that helps :slight_smile:


As a rule of thumb, one should avoid loops in R. Perhaps if you gave a little more information on what it is you are trying to accomplish, we could help you find a more R-ish way :slightly_smiling_face:

More information on how to get help, can be found here


Here's the loop in more idiomatic R:

List <- lapply(test, FUN = function(x) x[["data"]][[1]][["count"]])

(Sidenote: I wonder if your test object would be better off as a data.frame or array than a list)

People will often tell you "loops are slow in R," but this isn't necessarily true. It happens when people write loops in R like they would in other languages. It's shouldn't surprise us if any piece of code doesn't work well if run as-as in another language.

Assuming you're new to R, I suggest reading R Programming for Data Science (link is to the Vectorized Operations chapter, which applies here). After that, read The R Inferno for funny lessons on what idiomatic R is by seeing what isn't.

1 Like